How can I draw an array of objects inside another object in p5.js?

Solution 1:

You basically have three options 1) do the math to calculate the start and end points for each line based on the intersections between each line and the circle that they are to be drawn within; 2) draw your lines to a separate context, copy the content to an Image, and then use the p5.Image.mask function; or 3) draw your lines to a separate context, and then use either the erase() function or blendMode(REMOVE) to clear the portion of that context that is not inside the circle (this would require an additional mask shape as well).

Since you are already drawing to a separate context, here is an example that uses an image mask (i.e. #2):

let linhas = [];
let fundo2;
let img;
let maskCtx;

function setup() {
  createCanvas(400, 400);
  pixelDensity(1);
  fundo2 = createGraphics(400, 400);
  maskCtx = createGraphics(400, 400);
  maskCtx.noStroke();
  maskCtx.circle(200, 200, 250);
  img = createImage(width, height);
  for (let i = 0; i < 100; i++) {
    let x = random(0, 400);
    let y = random(0, 400);
    let z = random(0, 400);
    let w = random(0, 400);
    linhas[i] = new Linha(x, y, z, w);
  }
}

function draw() {
  circulo();
  tracos();
}

function tracos() {
  for (let linha of linhas) {
    linha.display();
    linha.tremer();
  }
}

function circulo() {
  img.copy(fundo2, 0, 0, width, height, 0, 0, width, height);
  img.mask(maskCtx);
  image(img, 0, 0, width, height);
  fundo2.noStroke();
  fundo2.circle(200, 200, 250);
}

class Linha {
  constructor(x, y, z, w) {
    this.x = x;
    this.y = y;
    this.z = z;
    this.w = w;
  }

  display() {
    fundo2.stroke(255, 0, 0, 70);
    fundo2.strokeWeight(2);
    fundo2.line(this.x, this.y, this.z, this.w);
  }
  tremer() {
    this.x = this.x + random(-1, 1);
    this.y = this.y + random(-1, 1);
    this.z = this.z + random(-1, 1);
    this.w = this.w + random(-1, 1);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>