Draw a Row of Windows on the Top Floor of a Building
To draw a row of windows, we are going to use a for loop. A for loop allows
us to perform a set of actions over and over again.
In this example, we draw a line of French flags.
We start by saving the original drawing state and moving the coordinate system to (140, 20).
This is where we will draw the first French flag.
context.save(); // Save the original drawing state
context.translate(140, 20); // Move the coordinate system to the top left corner of the first flag
Then, we start the for loop by assigning
var i = 0
.
Everytime through the loop, we increase
i
by one using the statement
i = i + 1
.
for (i = 0; i < 6; i = i + 1) {
// code block
}
So, the first time through the loop,
i == 0
.
The second time,
i == 1
.
The third time,
i == 2
.
The loop keeps running as long as
i < 6
.
This means the loop will run six times and end after
i == 5
.
Inside of the loop, we draw a French flag at the origin of the current
coordinate system, and then move the origin of the coordinate system 50 pixels
down using the
context.translate()
method.
for (i = 0; i < 6; i = i + 1) { // Repeat the code in the code block six times
drawFrenchFlag();
context.translate(0, 50); // Move the coordinate system to the top left corner of the next flag
}
Finally, we restore the drawing state so the origin of the coordinate system is back at the top left corner of the canvas.
context.restore(); // Restore the original drawing state
What would happen if, instead of using context.translate(30, 50) inside of the for loop, we used context.translate(0, 50)?
To learn more about for loops and translating the origin of the coordinate system, visit the
For Loops
and
translate()
lessons.
Quick Reference:
For Loops
save() / restore()
translate()