CanvasRenderingContext2D: isPointInPath() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

CanvasRenderingContext2D.isPointInPath() 方法是 Canvas 2D API 的一部分,用於報告指定的點是否包含在當前路徑中。

語法

js
isPointInPath(x, y)
isPointInPath(x, y, fillRule)
isPointInPath(path, x, y)
isPointInPath(path, x, y, fillRule)

引數

x

要檢查的點的 x 軸座標,不受上下文當前變換的影響。

y

要檢查的點的 y 軸座標,不受上下文當前變換的影響。

fillRule

用於確定點是在路徑內還是在路徑外的演算法。可能的值

nonzero

非零環繞規則。預設規則。

evenodd

奇偶纏繞規則

路徑

一個 Path2D 路徑,用於進行檢查。如果未指定,則使用當前路徑。

返回值

一個布林值。

一個布林值,如果指定的點包含在當前或指定的路徑中,則為 true,否則為 false

示例

檢查當前路徑中的點

此示例使用 isPointInPath() 方法來檢查一個點是否在當前路徑內。

HTML

html
<canvas id="canvas"></canvas>
<p>In path: <code id="result">false</code></p>

JavaScript

js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const result = document.getElementById("result");

ctx.rect(10, 10, 100, 100);
ctx.fill();
result.innerText = ctx.isPointInPath(30, 70);

結果

檢查指定路徑中的點

每當您移動滑鼠時,此示例都會檢查游標是否在一個圓形的 Path2D 路徑中。如果是,圓圈會變綠,否則會變紅。

HTML

html
<canvas id="canvas"></canvas>

JavaScript

js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// Create circle
const circle = new Path2D();
circle.arc(150, 75, 50, 0, 2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill(circle);

// Listen for mouse moves
canvas.addEventListener("mousemove", (event) => {
  // Check whether point is inside circle
  const isPointInPath = ctx.isPointInPath(circle, event.offsetX, event.offsetY);
  ctx.fillStyle = isPointInPath ? "green" : "red";

  // Draw circle
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fill(circle);
});

結果

規範

規範
HTML
# dom-context-2d-ispointinpath-dev

瀏覽器相容性

Gecko 特有說明

  • 在 Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4) 之前,此方法錯誤地未能將指定點的座標乘以當前變換矩陣,然後與路徑進行比較。現在,即使上下文被旋轉、縮放或以其他方式變換,此方法也能正常工作。

另見