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

浏览器兼容性

另见