Closest Point on Path
A black cardinal-interpolated path connects ten fixed points. As the mouse moves over the SVG canvas, a red line and circle dynamically trace the nearest location on that path to the cursor. The example demonstrates an approximate algorithm built on D3 v3’s SVG path API, using `getTotalLength` and `getPointAtLength` for a coarse linear scan followed by a binary search to refine the result to roughly one pixel accuracy.
AI-generated descriptionThis page demonstrates a simple approximate algorithm for finding the closest point on any given SVG path element. Although the algorithm is not guaranteed to return the best answer, the answer is reasonably good, and the accuracy is tunable at the expense of performance. It is based on Mike Kamermans’ excellent Primer on Bézier Curves.
A coarse linear scan of the path provides an initial guess. Then, a binary search improves the guess to the desired level of precision (here, about 1px). The coarseness of the initial scan is configurable; for paths where there may be multiple close points at different lengths along the path, such as at intersections, a finer initial scan is needed to avoid converging on a suboptimal answer.
Knowing the closest path to a given point is useful for multi-line charts in the same way the Voronoi tessellation is useful for scatterplots: it makes it easier to select or highlight elements using the mouse. Instead of requiring the user to hover over a line precisely, you can use this algorithm to find the line closest to the mouse. Alternatively, you can compute a Voronoi diagram for lines by sampling points along each path.