Square Space Fractal

This sketch is composed of black and white square spaces, with each space, except at the lowest level, containing four spaces of one quarter its width and height, placed in randomized positions.

The spaces are reconfigured during each frame. A mouse click toggles the action off and on.

p5.js code:

// Square Space Fractal
// September 6, 2021
// @javagar

new p5(function(p) { // anonymous p5 instance

  let fractal_depth = 4; // render fractal at 5 levels, including level 0
  let anim = true; // initialize animation to on

  p.setup = function() {
    p.createCanvas(2 ** (fractal_depth * 2 + 1), 2 ** (fractal_depth * 2 + 1));
    p.noStroke();
    p.noSmooth();
    p.frameRate(1);
  }

  p.draw = function() {
    if (anim) { // render the image, if animation is in effect
      rsqr(0, 0, p.width, p.height, 0, fractal_depth); // depth of 4 (5 levels with lowest depth of 0)
    }
  }

  let toggleAnimation = function () { // mouse click toggles animation off and on
    anim = !anim;
    if (anim) {
      p.loop();
    } else {
      p.noLoop();
    }
  }

  document.addEventListener('click', toggleAnimation, true);

  let rsqr = function(x, y, w, h, f, d) {
    p.push();
    p.fill(f);
    p.rect(x, y, w, h);

    if (d > 0) { // if depth > 0, recursive case
      d -= 1;
      w = w / 4; // divide width by 4 for next lower level
      h = h / 4; // divide height by 4 for next lower level
      if (f == 0) { // reverse the fill (black or white)
        f = 255;
      } else if (f == 255) {
        f = 0;
      }
      // render four square space fractals in randomized positions at next lower level
      rsqr(x + w / 2 + p.random(-w / 4, w / 4), y + h / 2 + p.random(-h / 4, h / 4), w, h, f, d);
      rsqr(x + 5 * w / 2 + p.random(-w / 4, w / 4), y + h / 2 + p.random(-h / 4, h / 4), w, h, f, d);
      rsqr(x + w / 2 + p.random(-w / 4, w / 4), y + 5 * h / 2 + p.random(-h / 4, h / 4), w, h, f, d);
      rsqr(x + 5 * w / 2 + p.random(-w / 4, w / 4), y + 5 * h / 2 + p.random(-h / 4, h / 4), w, h, f, d);
    }
    // else {}; // base case when depth is 0; do nothing more; else block is unnecessary
    p.pop();
  } // end function rsqr
} // end function(p) block
); // end anonymous p5 instance

EDITED on September 6, 2021 to make a revision to the code.

4 Likes

I don’t know why, but somehow your sketch reminded me of a JRubyArt context free art sketch:-

.
Not a Square space fractal but this JRubyArt CF3 example is:-
levy

2 Likes