There are two main types of loops. I will introduce you to them. However, we have been using a significant loop this whole time. It’s called draw.
To create a for loop, it looks like this.
function setup()
{
createCanvas(600,800);
}
function draw()
{
for(var i = 0; i < 5; i++)
{
console.log(i);
}
}
Try it out. It should print out all the numbers fro 0 to 4. Did you get that? Great!
The other type of loop is a while loop.
It looks something like this.
function setup()
{
createCanvas(600,800);
}
function draw()
{
var i = 0;
while(i < 5)
{
console.log(i);
i++;
}
}
Let’s use these to print the numbers to the screen.
var x = 0;
function setup()
{
createCanvas(600,800);
frameRate(10);
}
function draw()
{
background(255);
for(var i = 0; i < 5; i++)
{
textSize(28);
text(i,x,100);
x+=100;
}
x = 0;
}
Do you see all the numbers? That’s because we are printing them out to the screen using a for loop. Cool huh? Can we do this with a while loop too?
var x = 0;
function setup()
{
createCanvas(600,800);
}
function draw()
{
var i = 0;
while(i < 5)
{
textSize(28);
text(i,x,100);
x+=100;
i++;
}
x = 0;
}
These are useful; however, we won’t revisit this in detail until we get to arrays. So, keep this in your back pocket.
See the Pen p5.js Loops by Michael Cassens (@retrog4m3r) on CodePen.