HTML Canvas - restore() Method



The HTML Canvas restore() method is used to restore the saved canvas state from the state stack only if there is a saved state available, otherwise this method does not do anything.

Syntax

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

CanvasRenderingContext2D.restore();

Parameters

This method does not have any parameters as it just returns the previous canvas state if available.

Return value

This method returns a saved canvas state when called by the context object.

Example

The following example restores a saved rectangle onto the Canvas element using the HTML Canvas restore() method.

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

Output

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

HTML Canvas Restore Method

Example

The following example restores a circle which is saved in the stack using the method restore().

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="350" height="250" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.beginPath();
      context.save();
      context.fillStyle = 'cyan';
      context.arc(100, 100, 55, 0, 2 * Math.PI);
      context.fill();
      context.closePath();
      context.beginPath();
      context.restore();
      context.arc(250, 180, 55, 0, 2 * Math.PI);
      context.fill();
      context.closePath();
   </script>
</body>
</html>

Output

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

HTML Canvas Restore Method
html_canvas_shadows_and_transformations.htm
Advertisements