Managing State
The canvas context manages its drawing settings using a stack. Move the current state onto the stack and bring it back later after making temporary changes to styles or transformations.
| Method | Description |
|---|---|
save() |
Pushes the current state onto the stack. |
restore() |
Pops the last saved state from the stack and applies it back to the context. |
What is Saved?
Each state in the stack stores several items:
- The current transformation matrix (scaling, rotation, translation).
- The current clipping region.
- Drawing properties such as
fillStyle,font,lineWidth,shadowBlur, etc.
Canvas State Example
This example saves the state after each style change and subsequently restores them to redraw using the original settings:
The next lesson explains how to implement transformations like rotation and scaling.