Skip to content

Instantly share code, notes, and snippets.

@patakk
Last active August 22, 2022 13:17
Show Gist options
  • Save patakk/6f4d5205737d9865459574e4d99beef5 to your computer and use it in GitHub Desktop.
Save patakk/6f4d5205737d9865459574e4d99beef5 to your computer and use it in GitHub Desktop.
var rects = [];
function setup() {
createCanvas(800, 800);
noLoop();
var iterations = 6; // the number of times we'll do the split
rects.push([30, 30, width-30*2, width-30*2]); // initial square
for(var i = 0; i < iterations; i++){ // this can be done with recursion, but it's simple enough this way
var temp = []; // at each iteration we go through all current rectangles, split them, and put in a temp list
for(var k = 0; k < rects.length; k++){
var parts = splitRect(rects[k]);
temp.push(parts[0]);
temp.push(parts[1]);
}
rects = temp; // we'll now set our rects to the newly created temp list
}
}
function draw(){
background(20);
noFill();
stroke(220);
for(var k = 0; k < rects.length; k++){
rect(rects[k][0], rects[k][1], rects[k][2], rects[k][3]);
}
}
function splitRect(rec){
var x = rec[0];
var y = rec[1];
var w = rec[2];
var h = rec[3];
var p = random(.3, .7);
var r1, r2;
// I decided to make the split vertical if w>h, and vice-versa
// it can also be random or whatever
if(w > h){
r1 = [x, y, w*p, h];
r2 = [x+w*p, y, w*(1-p), h];
}
else{
r1 = [x, y, w, h*p];
r2 = [x, y+h*p, w, h*(1-p)];
}
return [r1, r2]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment