Skip to content

Lesson 5 of 9 · 26m

Hit Testing and Interaction on an Objectless Bitmap

Implement reliable picking with coordinate transforms, spatial indexes, color buffers, DOM overlays, and pointer-state machines that survive real input.

A canvas does not know what you clicked. It knows a pointer coordinate and nothing else. Every interaction layer on canvas is therefore a reconstruction of scene meaning. Build picking as a first-class system, or you will ship beautiful graphics that select the wrong thing and cannot be operated by keyboard.

Start with pointer events and local coordinates

canvas.addEventListener('pointerdown', event => {
  canvas.setPointerCapture(event.pointerId)
  dragStart = toCanvasPoint(event)
})

Pointer Events unify mouse, touch, and pen. Pointer capture keeps a drag alive when the cursor leaves the element. Convert coordinates once through the inverse of your camera transform; offsetX is input to that transform, not scene truth.

Use math for simple geometry

function hitCircle(point, circle) {
  const dx = point.x - circle.x, dy = point.y - circle.y
  return dx * dx + dy * dy <= circle.r * circle.r
}

Search objects from topmost to bottom. For lines, use distance-to-segment with a tolerance expressed in screen pixels and converted to scene units. A two-pixel visual line needs a larger clickable target.

Dense scenes need a spatial index — grid, quadtree, R-tree, or simple bins — so hit testing does not scan fifty thousand objects per pointer event. Insert shapes into every cell their bounds overlap and cache the index between mutations.

Color picking handles irregular rendered shapes

pickCtx.fillStyle = `rgb(${id & 255},${(id >> 8) & 255},${(id >> 16) & 255})`
drawShape(pickCtx, shape)

Read one pixel and decode the object id. This matches curves, holes, rotation, and clipping exactly as rendered. It also costs a raster pass and possible GPU readback, so run it when interaction requires it rather than on every pointermove.

DOM overlays beat fake controls

<canvas id="chart"></canvas>
<button class="point-marker" style="left: 240px; top: 130px">Inspect outage</button>

Real HTML gives focus, keyboard activation, labels, and accessibility semantics. Position overlays with the same projection function that draws the scene.

Dragging is a state machine

Use explicit states: idle, possible drag, dragging, settle. A click that moves two pixels should still be a click. Store the original object coordinates and apply deltas from the initial pointer position: origin + (currentPointer - startPointer) / zoom. Incremental float accumulation drifts and becomes jittery under zoom.

Field notes

  • Coarse pointers need larger hit tolerances than visual precision suggests.
  • Set touch-action deliberately; browser scrolling and canvas dragging otherwise fight each other.
  • Hidden color buffers must avoid antialiased edge blending or boundary pixels decode as nonexistent IDs.
  • Track preview state during drag and commit once on release if undo or consistency matters.
  • Coalesce expensive hit testing into the animation frame instead of running it for every pointermove event.

Was this lesson helpful?

Sign in to rate