HTML Canvas - clip() 方法



HTML Canvas 的clip() 方法是CanvasRenderingContext2D 介面的一部分,可用於將 Canvas 區域上的當前可用路徑更改為新的裁剪區域。

我們可以透過新增各種樣式和當前路徑來更改裁剪區域。這會特別裁剪之前的路徑並將新的路徑資料新增到其中。

語法

以下是 HTML Canvas clip() 方法的語法:

CanvasRenderingContext2D.clip(path, fillrule);

引數

以下是此方法的引數列表:

序號 引數和描述
1 path

用於應用裁剪方法的路徑。

2 fillrule

用於檢查點是否在裁剪區域內或外的演算法。此方法的可能值為:

  • 非零 (non-zero)

  • 奇偶 (even-odd)

返回值

在畫布元素上呈現形成到當前路徑的裁剪區域。

示例

以下示例使用 HTML Canvas clip() 方法在 Canvas 元素上繪製一個圓圈並裁剪其中的部分割槽域。

<!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="200" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.beginPath();
      context.arc(100, 75, 50, 0, Math.PI * 2);
      context.clip();
      context.fillStyle = 'white';
      context.arc(0, 0, 50, 0, Math.PI * 1);
      context.fillStyle = 'black';
      context.arc(0, 0, 50, 0.2 * Math.PI, 0.3 * Math.PI);
      context.fill();
   </script>
</body>
</html>

輸出

上述程式碼在網頁上返回的輸出為:

HTML Canvas Clip Method

示例

以下程式在 Canvas 元素上繪製一個矩形,並使用 clip() 方法裁剪其中的部分割槽域。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="260" height="200" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.beginPath();
      context.rect(20, 20, 200, 150);
      context.stroke();
      context.clip();
      context.fillStyle = 'grey';
      context.fillRect(0, 0, 150, 100);
   </script>
</body>
</html>

輸出

上述程式碼在網頁上返回的輸出為:

HTML Canvas Clip Method
html_canvas_paths.htm
廣告
© . All rights reserved.