I wrote this little snippet of code in Processing, that draws rectangles via a loop… each rectangle is slighty wider as the code loops through the rows… So far so good… But what I actually would like to achieve is that in the first row is 1 rectangle, in the second row 2, in the third 3 and so on… in other words, that every row has as many rectangles in it as its row number… But I am really stuck here. I thought of a nested loop. With that I can draw in X and Y axis… but how to combine that with the with? Does this have something with fractals to do?
Here ist my little snippet:
int rows = 100;
void setup() {
size(1080, 1080);
rectMode(CENTER);
}
void draw() {
background(0);
fill(255);
translate(0, height/rows/2);
for (int y=0; y < rows; y ++) {
rect(width/2, (height/rows)*y, width/rows*y, height/rows);
}
}
Thank you for any kind of help!
All the best and thank you! I added a picture that shows what I try to achieve:
Laancelot's solution is elegant(+1).
Here is a commented variation using nested for loops:
void setup() {
size(1024, 512);
noFill();
stroke(255);
strokeWeight(3);
background(0);
// number of rows: this should fill the screen, more will be hard to see
int rows = 6;
// the initial height of a box
float boxHeight = height / 2;
// the initial y position of the box
float y = boxHeight;
// the initial number of boxes
int hCount = 2;
// for each row
for(int row = 0; row < rows; row++){
// compute the width per box
float boxWidth = width / hCount;
// for each box per row
for(int i = 0; i < hCount; i++){
// draw the box, offset on X
rect(boxWidth * i, y, boxWidth, boxHeight);
}
// increment values for next row...
// half the height
boxHeight /= 2;
// move boxes lower
y += boxHeight;
// draw twice as many boxes on the next row
hCount *= 2;
}
}
You can run a demo bellow:
function setup() {
createCanvas(1024, 512);
noFill();
stroke(255);
strokeWeight(3);
background(0);
// number of rows: this should fill the screen, more will be hard to see
let rows = 6;
// the initial height of a box
let boxHeight = height / 2;
// the initial y position of the box
let y = boxHeight;
// the initial number of boxes
let hCount = 2;
// for each row
for(let row = 0; row < rows; row++){
// compute the width per box
let boxWidth = width / hCount;
// for each box per row
for(let i = 0; i < hCount; i++){
// draw the box, offset on X
rect(boxWidth * i, y, boxWidth, boxHeight);
}
// increment values for next row...
// half the height
boxHeight /= 2;
// move boxes lower
y += boxHeight;
// draw twice as many boxes on the next row
hCount *= 2;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.2.0/p5.min.js"></script>
This seems related to a fractal, the Cantor Set in particular.