Use translate() to Position the Building
Now we are going to clean up our functions a little bit.
A well-written function is like a polite robot who comes over to your house
to do a job, and then leaves everything exactly as it found it. But if you
look at the function used to draw a French flag in the previous example, it
wasn't so tidy. It changed the context.fillStyle to '#EF4135' and never
changed it back.
To make our function more tidy, we are going to call context.save() at the
start of the function and context.restore() at the end of the function.
Calling context.save() saves the state of the context (including the current
context.fillStyle), and context.restore() restores the context to the last
time you saved it.
The other change we are going to make to our function is to use context.translate().
Notice how we had to do some calculations with x and y to figure out the positions
of the white and red rectangles in the French flag? Imagine you had to do the same
calculations for a hundred windows in a building. By using context.translate(), we can
eliminate a lot of that math.
Calling context.translate() moves the origin of the context. If we move the origin
of the context to the top left corner of the flag, then we can draw the rectangles
in the flag as though the flag is positioned at (0, 0). The math is much easier.
However, when using context.translate(), it's even more important to save and then
restore the context. If you think changing the context.fillStyle is rude, changing
the origin of the context and not changing it back is much ruder!
(As an exercise, try to predict what would happen if you took out the context.save()
and context.restore() from the function. You'll have to reset the example and then
refresh the entire page to get everything back to normal.)
save() / restore()