Course contentsShow
← Web Development
Lesson 2622 of 2,98247. Data VisualizationFree lesson

Saving and Restoring State

Using save and restore to manage canvas state stack for complex drawing operations.

Saving and Restoring State

You'll learn how to use canvas state management to preserve and restore drawing configurations when working with complex layered graphics.

The Problem of Canvas State

When you draw on the canvas and apply transformations or style changes (like rotations, translations, fills, or line widths), those changes affect everything drawn afterward. Imagine painting a picture where every brush stroke permanently changes your entire palette and canvas angle—chaos!

The State Stack Solution

The canvas provides save() and restore() methods that work like a time machine for your drawing settings. Think of save() as taking a snapshot of your current canvas configuration (transformations, styles, clipping regions) and pushing it onto a stack. restore() pops that snapshot off the stack and rewinds to that exact state.

const ctx = canvas.getContext('2d');

// Initial state: black, no transforms
ctx.fillStyle = 'black';

ctx.save(); // Save State 1 (black)

ctx.fillStyle = 'red';
ctx.translate(50, 50);
ctx.fillRect(0, 0, 30, 30); // Red square at (50, 50)

ctx.save(); // Save State 2 (red + translated)

ctx.fillStyle = 'blue';
ctx.rotate(Math.PI / 4);
ctx.fillRect(0, 0, 20, 20); // Blue rotated square

ctx.restore(); // Back to State 2 (red + translated)
ctx.fillRect(40, 0, 30, 30); // Red square, no rotation

ctx.restore(); // Back to State 1 (black, no transform)
ctx.fillRect(0, 0, 30, 30); // Black square at (0, 0)

When to Use It

Use save() before making temporary changes (drawing a component with unique transforms/styles), then restore() to avoid contaminating subsequent drawings. Essential for modular, reusable drawing functions.

Key Takeaway: save() and restore() manage a stack of canvas states, letting you isolate drawing operations without side effects—critical for complex visualizations with multiple transformed elements.