CanvasRenderingContext2D: isPointInPath() 方法
CanvasRenderingContext2D.isPointInPath() 方法是 Canvas 2D API 的一部分,用于报告指定的点是否包含在当前路径中。
语法
js
isPointInPath(x, y)
isPointInPath(x, y, fillRule)
isPointInPath(path, x, y)
isPointInPath(path, x, y, fillRule)
参数
返回值
- 一个布尔值。
-
一个布尔值,如果指定的点包含在当前或指定的路径中,则为
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) 之前,此方法错误地未能将指定点的坐标乘以当前变换矩阵,然后与路径进行比较。现在,即使上下文被旋转、缩放或以其他方式变换,此方法也能正常工作。
另见
- 定义此方法的接口:
CanvasRenderingContext2D