Search code examples
javascriptgridp5.js

How to make a grid of moiré circles in p5.js?


I'm attempting to make a grid where every tile is filled with a single "moire-style" ellipse (a circle with circles inside).

function setup() {
  createCanvas(500, 500);
  ellipseMode(CENTER);
}

function draw() {
  background(255);
  noFill();
  strokeWeight(3);
  stroke(0);

  let tilesX = 3;
  let tilesY = tilesX;

  let tileW = width / tilesX;
  let tileH = height / tilesY;

  for (let x = 0; x < tilesX; x++) {
    for (let y = 0; y < tilesY; y++) {
      moire(tilesX, tilesY, tileW);

    }
  }

  function moire(x, y, size) {
    for (var i = 1; i <= tileW; i = i + 8) {
      ellipse(width / 2, height / 2, 2 * i, 2 * i);
      translate(tilesX, tilesY);

    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.js"></script>

This is what I have in my p5.js sketch but the moire elements don't align to the tiles.


Solution

  • The following demo will create a grid of moire circles:

    let _numRows = 3;
    let _numCols = 3;
    let _colGap = 30;
    let _rowGap = 30;
    
    function moire(x, y, size) {
      for (var i = 1; i <= size; i = i + 8) {
        ellipse(x, y, 2 * i, 2 * i);
        translate(3, 3);
      }
    }
    
    function setup() {
      createCanvas(500, 500);
      ellipseMode(CENTER);
    }
    
    function draw() {
      background(255);
      noFill();
      strokeWeight(3);
      stroke(0);
      let _xOffset = width/5;
      let _yOffset = height/5;
      for (let j = 0; j < _numCols; j++) {
        for (let k = 0; k < _numRows; k++) {
          push();
          moire(_xOffset + j * (100 + _colGap), _yOffset + k * (100 + _rowGap), 50);
          pop();
        }
      }
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.js"></script>