HTML Canvas - save() Method



The HTML Canvas save() method of Canvas 2D API is used to save the entire state of the Canvas element by pushing the current state onto the state stack.

Syntax

Following is the syntax of HTML Canvas save() method −

CanvasRenderingContext2D.save();

Parameters

Since this method just saves the canvas state when called, it does not accept any parameters.

Return value

It does not directly return anything, rather stores the current state onto the stack when called.

Example

The following example saves a square in the state stack using the HTML Canvas state() method.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="210" height="150" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.save();
      context.strokeRect(25, 20, 150, 100);
   </script>
</body>
</html>

Output

The output returned by the following code on the webpage as −

HTML Canvas Save Method

Example

The following example saves a shape first and restores it onto the Canvas element using the HTML Canvas save() method.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="300" height="250" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.fillStyle = 'orange';
      context.fillRect(40, 40, 200, 150);
      context.save();
      context.fillStyle = 'white';
      context.fillRect(55, 55, 170, 120);
      context.save();
      context.fillStyle = 'green';
      context.fillRect(70, 70, 140, 90);
      context.restore();
      context.fillRect(85, 85, 110, 60);
      context.restore();
      context.fillRect(100, 100, 80, 30);
   </script>
</body>
</html>

Output

The output returned by the following code on the webpage as −

HTML Canvas Save Method
html_canvas_shadows_and_transformations.htm
Advertisements