Using loops - Griffith-ICT/1701ICT-Creative-Coding GitHub Wiki

Laying out shapes

It is quite common to want a grid of objects. In the following example we are going to draw 5 ellipses, 100 pixels apart:

for (var x = 50; x < 550; x = x + 100) {
    ellipse(x, 46, 55, 55);
}

Let's look at how we did it. We have decided to call the loop variable x since we will be modifying the x co-ordinate of the ellipse. It's initial value is 50, which will be the first x value of the ellipse. The x value has 100 added to it each time through the loop, this shifts the next ellipse 100 pixels to the right. The result is that x will have the following values:

50, 150, 250, 350, 450

Note that it never gets to 550, because the comparison is x < 550, since 550 < 550 is false then the loop ends. Note any value above 450 could've been used to end the loop.

Finally, we use the x variable as the first parameter in the ellipse() function in place of a raw value. This allows its value to change each time through the loop.

We could written the loop another way:

for (var i = 0; i < 5; i++) {
    ellipse(i * 100 + 50, 46, 55, 55);
}

This loop performs the same, however it is written differently. In this case the focus of the loop is that it loops 5 times. We have decided to use the i variable instead. It starts at 0 and only increments by 1 each time through the loop.

This would mean that the x values would be 0, 1, 2, 3, 4, which are two small. We want them to be much larger.

One way to achieve this is to multiple the loop value in i by a value, in this case 100. In JavaScript (and most programming languages) the asterisk is used for multiplication. The values of i * 100 will be:

0, 100, 200, 300, 400

However the first value of i is too small, it will be right on the edge of the canvas. We want to offset all of our values to the right. We can do this by simply adding the offset, which is why we add 50: i * 100 + 50

X and Y

One advantage of decoupling the loop variable from the x axis is that we can use it for multiple things.

We are now going to change both the x and y values:

for (var i = 0; i < 5; i++) {
    ellipse(i * 100 + 50, i * 50 + 30, 55, 55);
}

Note that we have used very similar code for the y axis as we did for the x axis. However, just to indicate that it is independent, we have used a smaller vertical distance between ellipses (50 pixels) and a smaller starting offset (30 pixels).

This code could be made easier to read by creating variables for the x and y axis. Note that this is not required, and is primarily done to make the code more readable:

for (var i = 0; i < 5; i++) {
    var x = i * 100 + 50;
    var y = i * 50 + 30;
    ellipse(x, y, 55, 55);
}

Changing colours

We can also use the loop to change the colour of the ellipse. In this case we will use it to change the alpha.

for (var i = 0; i < 5; i++) {
    fill(255, 100, 100, i * 50 + 20);
    var x = i * 100 + 50;
    var y = i * 50 + 30;
    ellipse(x, y, 55, 55);
}