HTML Canvas - isPointInPath() 方法



HTML Canvas 的 isPointInPath() 方法是 Canvas 2D API 的一部分,它檢查指定點是否包含在當前路徑中,並使用布林值輸出進行報告。

語法

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

CanvasRenderingContext2D.isPointInPath(x, y, path, rule);

引數

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

序號 引數及描述
1 x

要檢查的點的 x 座標。

2 y

要檢查的點的 y 座標。

3 path

要參考以檢查提供的點是否包含在其中的路徑。如果未給出路徑,則使用當前路徑。

4 rule

用於確定點是否在路徑中的演算法。此引數採用兩個輸入值。

  • nonzero

  • evenodd

返回值

CanvasRenderingContext2D 介面上下文物件訪問 isPointInPath() 方法時,它會返回一個布林值,指示點是否在路徑中。

示例 1

以下示例在 Canvas 元素中繪製一個圓圈,並使用 HTML Canvas isPointInPath() 方法檢查提供的點是否在路徑中。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body onload="Context();">
   <canvas id="canvas" width="200" height="200" style="border: 1px solid black;"></canvas>
   <p>Check the given point is in the path : <code id="check">false</code>
   </p>
   <script>
      function Context() {
         var canvas = document.getElementById("canvas");
         var context = canvas.getContext("2d");
         var check = document.getElementById("check");
         context.beginPath();
         context.arc(100, 100, 75, 1 * Math.PI, 5 * Math.PI);
         context.fill();
         context.closePath();
         check.innerText = context.isPointInPath(150, 150);
      }
   </script>
</body>
</html>

輸出

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

HTML Canvas IsPointInPath Method

示例 2

以下示例在 Canvas 元素中繪製一個描邊的三角形,並檢查提供的點是否在路徑中。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body onload="Context();">
   <canvas id="canvas" width="200" height="200" style="border: 1px solid black;"></canvas>
   <p>Check the given point is in the shape : <code id="check">false</code>
   </p>
   <script>
      function Context() {
         var canvas = document.getElementById("canvas");
         var context = canvas.getContext("2d");
         var check = document.getElementById("check");
         context.strokeStyle = 'blue';
         context.beginPath();
         context.moveTo(100, 50);
         context.lineTo(25, 150);
         context.lineTo(175, 150);
         context.lineTo(100, 50);
         context.stroke();
         context.closePath();
         check.innerText = context.isPointInPath(15, 15);
      }
   </script>
</body>
</html>

輸出

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

HTML Canvas IsPointInPath Method
html_canvas_paths.htm
廣告

© . All rights reserved.