Isolating transformations is very helpful when you have multiple elements that you want to transform individually on a canvas. As we have learned, all transformation functions accumulate—this is where the
pop() functions come in handy. By surrounding code blocks with the
pop() functions, you can isolate transformations to be applied to targeted elements and not affect any elements that come after it.
push() function saves the current style settings and transformations, while
pop() restores it back to the original settings.
The example code below shows how the
pop() functions can be used to contain style and transformation functions for a particular shape:
push(); translate(30,50); fill(255, 0, 0); rect(0, 0, 100, 100); pop();
Keep in mind that every
push() needs a
pop()! Also notice how the
push() function always comes before the
pop(). Sandwiched in-between
pop() are any style and transformation functions intended for one shape, but not for another.
Notice in pushpop.js on the right, we are able to isolate all three rectangles using
Isolate the code block for the yellow spiral using the
The code for the yellow spiral starts at the line:
and ends after the first
Notice how both yellow and blue spirals rotate at the center of the canvas!
Now, isolate the code block for the blue spiral. Even though encasing the code for the yellow spiral is enough to keep both spirals rotate at the center of the canvas, it is best practice to isolate code blocks that use transformation functions to prevent shapes added on later to the canvas from being affected.
The code for the blue spiral starts at the line:
and ends after the second