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
).
void setup() {
size(windowWidth, windowHeight);
background(100);
}
void draw() {
for (float x = 10; x <= width; x += 50) {
circle(x, 100, 40);
}
}
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 with your choice of canvas size:
//for example
void setup() {
createCanvas(600, 600);
}
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.
void draw() {
float x = 10;
for (int i = 0; i < 20; i++) {
circle(x, 100, 40);
x += 50;
}
}
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.
void draw() {
float x = 10;
for (int i = 0; i < 20; i++) {
circle(x, 100, 40);
x *= 1.2;
}
}
Changing the spacing is useful when the size changes too.
void draw() {
float x = 20;
float size = 5;
for (int i = 0; i < 20; i++) {
circle(x, 100, size);
x *= 1.15;
size *= 1.15;
}
}
Back to the arithmetic progression:
void draw() {
float x = 10;
for (int i = 10; i < 20; i++) {
circle(x, 100, 40);
x += 50;
}
}
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.
An alternative to accumulation is to derive the value of x
from scratch each time, directly from the value of i
. The shape position is derived from the loop index. This has the same effect as the previous code, but it will allow us to plug in different functions besides the linear function $x = 10 + 50i$ used here. We’ll see that later.