CanvasRenderingContext2D: isPointInStroke() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流瀏覽器均已支援。

CanvasRenderingContext2D.isPointInStroke() 方法(Canvas 2D API 的一部分)用於報告指定的點是否位於路徑描邊所包含的區域內。

語法

js
isPointInStroke(x, y)
isPointInStroke(path, x, y)

引數

x

要檢查的點的 x 軸座標。

y

要檢查的點的 y 軸座標。

路徑

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

返回值

一個布林值。

一個布林值,如果該點位於路徑描邊所包含的區域內,則為 true,否則為 false

示例

檢查當前路徑中的點

此示例使用 isPointInStroke() 方法檢查一個點是否位於當前路徑描邊區域內。

HTML

html
<canvas id="canvas"></canvas>
<p>In stroke: <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.stroke();
result.innerText = ctx.isPointInStroke(50, 10);

結果

檢查指定路徑中的點

每當滑鼠移動時,此示例都會檢查游標是否位於一個橢圓 Path2D 路徑的描邊內。如果是,則橢圓的描邊變為綠色,否則為紅色。

HTML

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

JavaScript

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

// Create ellipse
const ellipse = new Path2D();
ellipse.ellipse(150, 75, 40, 60, Math.PI * 0.25, 0, 2 * Math.PI);
ctx.lineWidth = 25;
ctx.strokeStyle = "red";
ctx.fill(ellipse);
ctx.stroke(ellipse);

// Listen for mouse moves
canvas.addEventListener("mousemove", (event) => {
  // Check whether point is inside ellipse's stroke
  const isPointInStroke = ctx.isPointInStroke(
    ellipse,
    event.offsetX,
    event.offsetY,
  );
  ctx.strokeStyle = isPointInStroke ? "green" : "red";

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

結果

規範

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

瀏覽器相容性

另見