Search code examples
svgpathcoordinatespoint

Get point's y coordinate on svg path


I guess I need to add some explanation, that I want to ask this question, because too short question doesn't quality standards... funny...

So, here is the question: How I can get the 'y' coordinate of the point on svg path at a specific 'x' coordinate?


Solution

  • Well this is not straightforward, because a path could have multiple points with the specified x coordinate.

    There is no built-in function in the SVG DOM to do this. One solution is to step along the path segments and do the maths yourself.

    Alternatively, there is a built in function on SVGPathElement called getPointAtLength(len). You pass in a length along the path and it will return the x,y coords at that point. You could step along the path length and work out where the x coordinate crosses your desired x. You can get the path length from the SVGPathElement.getTotalLength() function. It's a bit of a kludge and you have to be careful you don't miss points where the curve bends near your x. But it should work.

    See here for more information on these functions.