← 中文资源

简体中文版本

Canvas isPointInPath 命中检测

把圆形与三角形各画成 Path2D,逐个用 ctx.isPointInPath(path, x, y) 询问坐标是否落在内部;重叠区两个形状同时命中,返回全部匹配者。

阅读英文原文

实现说明

Canvas isPointInPath 命中检测以函数 hitTest为骨架。

使用要点

  • 用到了 document,需要在浏览器环境运行,Node 里直接跑会缺 API。
  • 演示输出是带标签的(circle center:、overlap zone:、triangle only:),每个操作都会留下自己的一行标注。

常见问题

「Canvas isPointInPath 命中检测」能在裸 Node.js 里跑吗?

不能——document 的家在浏览器里,Node 进程提供不了。执行时请用页面(或 DevTools 控制台)。

主签名形如 function hitTest(x, y)

核心语句

return shapes.filter((shape) => ctx.isPointInPath(shape.path, x, y)).map((s) => s.label);

代码示例

// Canvas hit testing: build shapes as Path2D objects and ask
// isPointInPath whether a coordinate lands inside each one
const canvas = document.createElement('canvas');
canvas.width = 220;
canvas.height = 130;
const ctx = canvas.getContext('2d');

const circle = new Path2D();
circle.arc(60, 60, 40, 0, Math.PI * 2);

const triangle = new Path2D();
triangle.moveTo(90, 20);
triangle.lineTo(130, 100);
triangle.lineTo(50, 100);
triangle.closePath();

const shapes = [
  { path: circle, label: 'circle' },
  { path: triangle, label: 'triangle' },
];

function hitTest(x, y) {
  return shapes.filter((shape) => ctx.isPointInPath(shape.path, x, y)).map((s) => s.label);
}

console.log('circle center:', hitTest(60, 60));
console.log('overlap zone:', hitTest(85, 60));
console.log('triangle only:', hitTest(95, 90));
console.log('outside both:', hitTest(10, 120));