Canvas isPointInPath Hit Tests Shapes

Build shapes as Path2D objects and ask ctx.isPointInPath per pointer coordinate, returning every shape that contains the point.

JavascriptData Integrity

Code

javascriptsnippet
29 lines
// 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));

Inside the snippet

Canvas isPointInPath Hit Tests Shapes is built around the function hitTest.

Caveats

  • The snippet leans on document — browser-only surfaces a bare Node process cannot provide.

Putting it to use

Entry signature: function hitTest(x, y)

The run prints circle center:, overlap zone:, triangle only: — each prefix names the step that produced it.

Core lines

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

Interactive Tools for This Topic

FAQ

Does Canvas isPointInPath Hit Tests Shapes run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.