Learn

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 push() and pop() functions come in handy. By surrounding code blocks with the push() and pop() functions, you can isolate transformations to be applied to targeted elements and not affect any elements that come after it.

The 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 push() and 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 push() and 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 push() and pop().

Instructions

1.

Open sketch.js.

Isolate the code block for the yellow spiral using the push() and pop() functions.

The code for the yellow spiral starts at the line:

translate(yellowX, yellowY);

and ends after the first for loop.

Notice how both yellow and blue spirals rotate at the center of the canvas!

2.

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:

translate(blueX, blueY);

and ends after the second for loop.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?