Use Transformations in a For Loop
While using the value of the counter to position drawings inside of a for loop
works, it's often simpler to position drawings by using transformations. You will
need to be familiar with the
context.save()
and
context.translate()
methods to understand this example and complete the following challenge.
In this example, we draw a grid of lines using two separate for loops. We start
by translating to the top left corner of the grid, which is at coordinates (0, 0),
setting the
context.strokeStyle
property, and saving the drawing state:
context.translate(10, 10);
context.strokeStyle = 'Crimson';
context.save(); // The origin of the coordinate system is at the top left corner of the grid
We save the drawing state because we will want to restore the origin of the coordinate
system back to the top left corner of the grid later.
Next, we create the first for loop to draw 17 vertical lines that are 240 pixels
long and 20 pixels apart.
for (var i = 0; i < 17; i = i + 1) {
context.beginPath();
context.moveTo(0, 0);
context.lineTo(0, 240);
context.stroke();
context.translate(20, 0);
}
Note that we are drawing each line from (0, 0) to (0, 240). To position each line
20 pixels over from the previous line, we use the
context.translate()
method to move the entire coordinate system 20 pixels to the right.
Once the first for loop is finished, we are ready to draw the horizontal lines in
our grid, but the origin of the coordinate system is currently 20 pixels to the right
of the last vertical line drawn. Before we can draw our horizontal lines, we need to
restore the origin back to the top left corner of the grid:
context.restore(); // Restores the origin of the coordinate system back to the top left corner of the grid
Finally, we create the second for loop to draw 13 horizontal lines that are 320 pixels
long and 20 pixels apart.
for (var j = 0; j < 13; j = j + 1) {
context.beginPath();
context.moveTo(0, 0);
context.lineTo(320, 0);
context.stroke();
context.translate(0, 20);
}
Once again, we are drawing the same line from (0, 0) to (320, 0) each time
through the loop. To position each line 20 pixels down from the previous line, we use the
context.translate()
method to move the entire coordinate system 20 pixels down.
Because the second for loop happens after the first for loop, we could have
used the same counter,
i
,
for both loops. If we re-used the variable
i
in the second loop, we would still initialize it by assigning it the value of
0, but we would not declare it again.
To learn more about saving and restoring the drawing state, translating
the coordinate system, and drawing lines, visit the
save() / restore(),
translate(),
Coordinates,
and
lineTo()
lessons.
Quick Reference:
Coordinates
Variables
save() / restore()
translate()
lineTo()