Mastering Drawing Context Isolation in p5.js with push() and pop()
The p5.js rendering engine maintains a global transform matrix and a continuous set of visual properties. To prevent these configurations from persisting across multiple frame cycles, the library implements a context stack governed by push() and pop().
Invoking push() captures the current rendering environment and places it on a stack. This snapshot records all active styling directives—including fill colors, stroke weights, blend modes, and lighting states—alongside the exact coordinate transformation matrix applied at that moment. Executing pop() reverts the renderer to the previous stored context, discarding any attribute or spatial modifications introduced after the corresponding push() call.
Preserving Visual Styling
Wrapping configuration sequences in state boundaries prevents property leakage between successive draw operations.
function setup() {
createCanvas(480, 400);
}
function draw() {
background(240);
// Define and lock custom appearance
push();
fill(0, 180, 120);
strokeWeight(5);
rect(60, 80, 70, 70);
pop();
// Rendering returns to baseline configuration
rect(200, 80, 70, 70);
}
The initial rect renders with the specified teal hue and thick border. Once pop() executes, those temporary overrides are discarded, ensuring the second shape adheres strictly to the default drawing conditions.
Containing Coordinate Transforms
Spatial manipulations fundamental shift the origin point. Encapsulating geometry within state markers guarantees the underlying mathematical grid remains unperturbed for later calculations.
const TAU = Math.PI * 2;
function setup() {
createCanvas(480, 400);
}
function draw() {
background(230);
// Apply angular offset temporarily
push();
let pivotAngle = TAU / 8;
rotate(pivotAngle);
ellipse(150, 200, 60, 60);
pop();
// Subsequent primitives ignore prior rotation
ellipse(150, 200, 60, 60);
}
The first geometric primitive appears tilted becuase the transformation matrix was altered mid-draw. The subsequent pop() restores the matrix to its original identity state, anchoring the next shape to the unmodified coordinate system. Omitting these boundaries causes cumulative matrix multiplication, resulting in rapid positional drift across consecutive frames.