HTML 畫布 - restore() 方法



HTML 畫布 restore() 方法用於從狀態棧恢復已儲存的畫布狀態,但僅當有可用的已儲存狀態時,否則此方法不起作用。

語法

以下是 HTML 畫布 restore() 方法的語法:

CanvasRenderingContext2D.restore();

引數

此方法不包含任何引數,因為它只在有可用狀態時返回上一個畫布狀態。

返回值

由環境物件呼叫時,此方法返回已儲存的畫布狀態。

示例

以下示例使用 HTML 畫布 restore() 方法將已儲存的矩形還原到畫布元素中。

<!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>

輸出

以下是以下程式碼在網頁上返回的輸出:

HTML Canvas Restore 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>

輸出

以下是以下程式碼在網頁上返回的輸出:

HTML Canvas Restore Method
html_canvas_shadows_and_transformations.htm
廣告
© . All rights reserved.