SyntaxStudy
Sign Up
HTML Saving and Restoring Canvas State
HTML Intermediate 5 min read

Saving and Restoring Canvas State

Canvas State Stack

save() pushes the current drawing state (transforms, styles, clip) to a stack. restore() pops the most recent saved state. They do not affect pixel content.

Example
const ctx = canvas.getContext("2d");

ctx.fillStyle = "blue";
ctx.save();                    // State 1: blue fill

  ctx.fillStyle = "red";
  ctx.save();                  // State 2: red fill

    ctx.fillStyle = "green";
    ctx.fillRect(20, 20, 80, 80); // green

  ctx.restore();               // Back to State 2: red
  ctx.fillRect(120, 20, 80, 80); // red

ctx.restore();                 // Back to State 1: blue
ctx.fillRect(220, 20, 80, 80); // blue
Pro Tip

Think of save/restore like a stack of settings snapshots — every restore() undoes the most recent save().