HTML Canvas - save() 方法



Canvas 2D API 的 HTML Canvas save() 方法用於透過將當前狀態推到狀態堆疊上來儲存 Canvas 元素的整個狀態。

語法

以下是 HTML Canvas save() 方法的語法 −

CanvasRenderingContext2D.save();

引數

由於此方法在呼叫時只是儲存畫布的狀態,所以它不接受任何引數。

返回值

它不會直接返回任何內容,而是在呼叫時將當前狀態儲存到堆疊中。

示例

以下示例使用 HTML Canvas state() 方法將一個正方形儲存在狀態堆疊中。

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

輸出

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

HTML Canvas Save Method

示例

以下示例先儲存一個形狀,然後使用 HTML Canvas save() 方法將其還原到畫布元素中。

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

輸出

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

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