Search code examples
javascriptdomsvgposition

How can I get the x/y coordinates of an SVG element(path etc) that does not have the X/Y attributes?


I am trying to get the position of SVG elements using Javascript. I have managed to get the position on elements that have X/Y attribute set. But elements, such as paths does not have this attribute.. At least not in my docuements.

Is there a way to calculate the position other than taking the first number in the "path"?

Thank you, Morten


Solution

  • You can use the function getBBox() to get the bounding box for the path. This will give you the position and size of the tightest rectangle that could contain the rendered path.

    An advantage of using this method over reading the x and y values is that it will work with all graphical objects. There are more objects than paths that do not have x and y, for example circles that have cx and cy instead.

    Link: getBBox() in the SVG v1.1 standard.