仅在 P5.js 的边界内绘制形状

Only draw shapes within a boundary in P5.js

我这里有这个例子:https://editor.p5js.org/agjones91/sketches/v6N5UlCAz

代码很简单,在随机位置创建 100 个圆圈,顶部是一个正方形。我需要做的是裁剪圆圈以仅在正方形内显示它们。正方形外的圆圈部分无法显示

function setup() {
  createCanvas(400, 400);
  noLoop();
}

function draw() {
  background(220);
  noFill();
  translate(100, 100);
  for (var i = 0; i < 100; i++) {
    var circleX = random(2, 50);
    var circleY = random(2, 50);

    circle(circleX, circleY, 100);
  }
  stroke("red");
  square(-25, -25, 100); //cop using this square
}

完成后,我需要在整个 canvas 中重复多次,因此无法使用覆盖形状来覆盖外部。我需要圆圈不要画在某个边界之外。

由于上面评论中的@Alberto Sinigaglia 和图形用户,设法解决了这个问题:https://editor.p5js.org/agjones91/sketches/v6N5UlCAz

想法是将圆圈应用到一层(图形),然后使用另一层将其裁剪(遮罩)。请参阅下面的代码:

function setup() {
  createCanvas(400, 400);
  noLoop();
}

function draw() {
  background(220);

  img = createGraphics(width, height);
  img.noFill(); //apply styles to new graphics layer
  img.translate(100, 100); //apply translations to new graphics layer
  
  for (var i = 0; i < 100; i++) {
    var circleX = random(2, 50);
    var circleY = random(2, 50);
    img.ellipse(circleX, circleY, 100, 100); //apply shapes to new graphics layer
  }

  mk = createGraphics(width, height);
  mk.translate(75, 75);
  mk.rect(0, 0, 100, 100);

  imgClone = img.get();
  imgClone.mask(mk.get());

  image(imgClone, 0, 0);
}