Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Canvas 2D: saving and restoring drawing state

`save()` pushes the current drawing state onto a stack, and `restore()` pops and reinstates the most recently saved state. Neither method undoes changes to pixels.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

ctx.save();
ctx.restore();

CanvasRenderingContext2D.save/restore refers to two methods you call on the same 2D rendering context, such as ctx from canvas.getContext('2d'). Both take no arguments and return undefined. They belong to the Canvas 2D Web API, not ECMAScript, so a JavaScript engine alone does not guarantee their availability.

save() pushes a copy of the current drawing state onto that context's stack. restore() removes the top entry and makes that saved state current. Nested saves therefore unwind in reverse order: last in, first out (LIFO). If the stack is empty, restore() does nothing and does not throw.

The saved state includes the transformation matrix, clipping region, fill and stroke styles, and globalAlpha, among other settings. It does not include the current default path or the canvas pixels: restore() neither erases what you drew nor reverses edits to that path. Use beginPath() to start a new default path.

Pair save() and restore() when you want changes to affect only one part of a drawing. If the code between them might throw, call save() first, put that code in try, and call restore() in finally so the state is restored even on an exception.

Examples

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Canvas 2D: save and restore</title>
</head>
<body>
  <canvas id="canvas" width="1" height="1" hidden></canvas>
  <script>
    (() => {
      const ctx = document.getElementById("canvas").getContext("2d");
      if (!ctx) throw new Error("Canvas 2D is unavailable.");

      ctx.globalAlpha = 1;
      ctx.save();
      ctx.globalAlpha = 0.5;
      ctx.save();
      ctx.globalAlpha = 0.25;
      console.log(ctx.globalAlpha);

      ctx.restore();
      console.log(ctx.globalAlpha);
      ctx.restore();
      console.log(ctx.globalAlpha);

      ctx.globalAlpha = 0.125;
      ctx.restore(); // The stack is empty.
      console.log(ctx.globalAlpha);
    })();
  </script>
</body>
</html>

Result

0.25
0.5
1
0.125

With two nested saves, the console prints `0.25`, then the restored values `0.5` and `1`. The final `restore()` finds an empty stack, so `0.125` stays unchanged.

Related lessons

  • JavaScript · Lesson 26 · Intermediate · Version: 3

Sources