WEEK: 4
Active: January 31st - February 6th
Work Due: February 7th @ 9:00AM

Sandboxing with
push() & pop()

One way that we can be more explicit in our order of operations is through the use of the pop() & push() functions.

These functions always work together to create a “sandbox” where transformational functions, such as color and shape changes, are enacted on everything inside of the sandbox. However, outside, of the sandbox (i.e. code lines after the pop() function), the transformation functions are no longer applied.

In the below example, try commenting out the push/pop sandbox in line no.s 10 & 27, to see how the sandbox effects the example.

[ Code Download ] [ View on GitHub ] [ Live Example ]

To explicitly demonstrate this example, the below image makes clear which rectangle was drawn first and second.

Two rectangles, using push and pop

Nesting push & pop sandboxes

push() and pop() sandboxes can be nested within each other. This allows your to create hierarchical relationships of how transformational functions apply in your sketch.

This can be particularly useful for complex drawings or animations.

/* sandbox 1 */
push();
// some code

    /* sandbox 2 */
    // inside sandbox 1
    push();
    // some code
    //
    // end sandbox 2
    pop();

// only in sandbox 1 now

// end sandbox 1
pop();

// outside of both sandboxes

A Warning

For reasons I do not want to go into yet, know that if you use a translate() function inside of your draw() function, you are going to experience funny behavior where your work “disappears”. The work around for this is to wrap the translate() function inside of a push/pop-sandbox.

function draw() {

    // create a push/pop sandbox for translate
    push();
    translate( someValue, someValue );

    //
    // The rest of your code
    //

    pop();
    //close the sandbox
}

Previous section: