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) 之前,此方法错误地未能将指定点的坐标乘以当前变换矩阵,然后与路径进行比较。现在,即使上下文被旋转、缩放或以其他方式变换,此方法也能正常工作。

另见