Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 12.3 — Hit-Testing: Clicking Things on a Canvas
Data Visualization · Example 1 of 3

isPointInPath on 25 stations

Move the pointer over the stations: the hovered one turns orange and its name appears. Quay and Market overlap, so the later-drawn Market wins where they cross.

A canvas draws pixels and keeps no shapes, so it cannot tell you what was clicked. You find the mark under the pointer yourself, with the browser's shape test, a hidden colour canvas, a quadtree or a Delaunay diagram.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 4 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write stationAtPoint(stations, x, y, reach) using a quadtree built inside it, returning the station or null.

02

In the second example, make the hover text say edge when the pixel is partly transparent, nothing when empty, and the name only when alpha is 255.

Explain it without notes

01

Why can you not add a click handler to one dot on a canvas?

02

Compare isPointInPath and colour picking: when would you choose each?

isPointInPath on 25 stations

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Quay is drawn with radius 10.1 (12 docks)
the centre of Quay -> Market
Quay, 8 px further from Market than its centre -> Quay
Quay, 30 px away -> null
far from every station -> null
outside the canvas -> null
a point that is NaN -> null
every mark under the centre of Quay: Quay, Market
distance between Quay and Market: 13.0 px, radii 10.1 + 13.1