Arranging items in a line – by width

This code draws a line of items – as many as necessary to reach the edge of the canvas. In this case, the items are circles. The code can be adapted to draw squares, or more complicated figures composed of multiple shapes.

The code draws shapes as will fit in the canvas width (x <= width), spaced 50 pixels apart (x += 50).

function setup() {
	createCanvas(windowWidth, windowHeight);
	background(100);
}

function draw() {
	for (let x = 10; x <= width; x += 50) {
		circle(x, 100, 40);
	}
}

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/43bac90b-ba98-416b-8cae-11203776cc12/Untitled.png

Arranging items in a line – by item count

What if we want to draw a fixed number of items? This code draws exactly 20 items, no matter how wide the canvas is. It uses i to count the number of shapes, from 0 to 19.

function draw() {
	let x = 10;
	for (let i = 0; i < 20; i++) {
		circle(x, 100, 40);
		x += 50;
	}
}

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/11da5255-53dc-4366-b2a6-5732f42a2526/Untitled.png

Note: From here on, the definition of setup() is not shown. Each of the following code samples assumes that the sketch also contains a setup() function:

function setup() {
	createCanvas(windowWidth, windowHeight);
	background(100);
}

Geometric Progressions

The code above increases x by the same amount each step. This is an arithmetic progression.

We can also increase x by an increasing amount. This is a geometric progression.

function draw() {
	let x = 10;
	for (let i = 0; i < 20; i++) {
		circle(x, 100, 40);
		x *= 1.2;
	}
}

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/76042ea2-8908-4c93-83aa-274c795d4e98/Untitled.png

Changing the spacing is useful when the size changes too.

function draw() {
	let x = 20;
	let size = 5;
	for (let i = 0; i < 20; i++) {
		circle(x, 100, size);
		x *= 1.15;
		size *= 1.15;
	}
}

Screenshot of Safari (4-8-22, 9-36-22 AM).png

Accumulating versus deriving

Back to the arithmetic progression:

function draw() {
	let x = 10;
	for (let i = 10; i < 20; i++) {
		circle(x, 100, 40);
		x += 50;
	}
}

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/11da5255-53dc-4366-b2a6-5732f42a2526/Untitled.png

This strategy for computing the value of x accumulates a value. x starts out with a value (10); then each time through the loop, the value is updated.