Get y coordinate along SVG path with given x coordinate

I use raphael.js to draw a simple line graph of SVG as follows:

line graph

When the user hovered over the graph, id wanted to display a popover pointing to a line at position X of the cursor, and at position Y , where is the line for this position X :

cursors with popovers along the line

I need to take a path and find the Y coordinate for a given X coordinate.

+4
source share
1 answer

Based on @Duopixel D3's solution, I wrote the following function for my own use in pure javascript using the DOM API:

function findY(path, x) { var pathLength = path.getTotalLength() var start = 0 var end = pathLength var target = (start + end) / 2 // Ensure that x is within the range of the path x = Math.max(x, path.getPointAtLength(0).x) x = Math.min(x, path.getPointAtLength(pathLength).x) // Walk along the path using binary search // to locate the point with the supplied x value while (target >= start && target <= pathLength) { var pos = path.getPointAtLength(target) // use a threshold instead of strict equality // to handle javascript floating point precision if (Math.abs(pos.x - x) < 0.001) { return pos.y } else if (pos.x > x) { end = target } else { start = target } target = (start + end) / 2 } } 
+1
source

All Articles