There are two strategies for arranging items in a grid:
Use a single loop to iterate over the number of items; derive the x and y position from the item number.
Use a nested loop to iterate over the x positions and, for each x, iterate over the y positions (left sketches). If the item number is required, derive it from the values of x and y (right sketch).
This builds on Arranging a Line of Items. Here is a sketch from that page:
function setup() {
createCanvas(windowWidth, windowHeight);
}
function draw() {
for (let i = 0; i < 30; i++) {
let x = 20 + 50 * i;
circle(x, 100, 40);
}
}
The shape position is derived from the loop index, using the function $x = 10 + 50i$ used here.
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);
}
Derive y
from i
as well.
function draw() {
for (let i = 0; i < 30; i++) {
let x = 30 + 50 * i;
let y = 30 + 10 * i;
circle(x, y, 40);
}
}
Let’s start with the angled line from above, and just look at the x position.
function draw() {
for (let i = 0; i < 30; i++) {
let x = 30 + 50 * i;
let y = 30 + 50 * i;
circle(x, y, 20);
}
}
Instead of a diagonal line, where each x is greater than the previous x and each y is greater than the previous y, we would like to arrange the items on a grid. Here, each item is labelled with its index number. The x value increases from items 0 to 4, and then it resets back to the left side and increases again to 9, and so on.
We can use the modulo (remainder) operator %
to chop it into pieces. For an input sequence i = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 etc., the modulo operator i % 5
produces 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, etc. The sketch then multiples this by 50 to make the result more visible: 0, 50, 100, 150, 200, 0, 50, 100, 150, 200, 0, 50, etc.