Canvas States

What You’ll Learn
Canvas state is like a snapshot of your drawing context: styles, transforms, shadow settings, and the clipping region. You can push snapshots with save() and pop them with restore().
This is the easiest way to prevent changes (like shadows or rotations) from leaking into later drawings.
⚡ Quick Reference
ctx.save();
// change styles/transforms
ctx.restore();fillStyle, strokeStyle, lineWidth…Saved & restored
translate/rotate/scaleSaved & restored
globalAlpha / globalCompositeOperationSaved & restored
clip()Saved & restored
👀 Live Preview — Save/Restore in Action
Toggle which changes are applied inside a saved state (shadow, rotate, alpha). Then compare the drawings before and after restore.
Tip: If you use clip(), always wrap it in save/restore. Otherwise your clipping region will keep affecting future drawings.
Basic save()/restore()
Save state, change a style, draw something, then restore so later drawings aren’t affected.
ctx.save();
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 100);
ctx.restore();Nested States (Stack Behavior)
Each save() pushes another snapshot. restore() pops one level.
// base
ctx.fillStyle = 'blue';
ctx.fillRect(10, 10, 100, 100);
ctx.save();
ctx.fillStyle = 'red';
ctx.fillRect(30, 30, 100, 100);
ctx.save();
ctx.rotate(0.5);
ctx.fillStyle = 'green';
ctx.fillRect(50, 50, 100, 100);
ctx.restore(); // undo rotate + green
ctx.fillRect(70, 70, 100, 100); // red
ctx.restore(); // back to blue
ctx.fillRect(90, 90, 100, 100); // blue💡 Best Practices
Do
- Wrap temporary styles (shadow/alpha/composite) in
save()/restore() - Always scope
clip()with save/restore - Keep save/restore balanced (like braces)
- Use save/restore per object when drawing complex scenes
- Reset transforms each frame in animations (or use save/restore)
Don’t
- Forget to restore after transforms (rotation/scale will leak)
- Assume save/restore clears pixels (it doesn’t)
- Overuse deep state stacks inside tight loops without measuring
- Mix globalAlpha/composite changes without scoping (hard to debug)
- Leave a clip active and wonder why drawings disappear
❓ Frequently Asked Questions
clearRect() to clear pixels.Next: Canvas Text
Learn fillText(), strokeText(), fonts, and alignment.
4 people found this page helpful
