xxxxxxxxxx
47
/* Loops
There are a couple of different kinds of loop structures in JavaScript, but a 'for loop' is by far the most popular
For Loops have 4 parts: example for loop
for (let i=0; i<10; i=i+){
//do something
}
FIRST we initialize a variable to keep track of the number = lets call this a counter variable
let i=0;
Inside loops we tend to use short variable names such as i or j if they are just controlling the 'flow' of the loop.
SECOND we define the test condition for the loop, this gets evaluated (tested ) each time the loop is about to start. Our example we are testing if our counter variable is smallet than 10
i < 10;
THIRD we are (defining a way ) updating the counter variable that then gets evaluated at the end of the loop. We are getting the current value of the variable i and adding 1 to it.
i = i + 1;
FORTH, final part, is inside the { } we write the code that the we want repeated. Once the variable counter doesn't 'satisfy' the test i<10 the loop terminates.
*/
function setup() {
createCanvas(800, 300);
}
function draw() {
background(1, 75, 100);
// circle properties
fill(237, 34, 93);
noStroke();
let diameter = 40;
for (let i=0; i<width/diameter; i=i+1) {
for (let j=0; j<height/diameter; j=j+1) {
ellipse(
diameter/2 + i * diameter,
diameter/2 + j * diameter,
diameter * random(), // using the random function
diameter
);
}
}
}