views:

106

answers:

1

Hi!

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

A: 

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.

There is more information about getBBox() as well as some code examples on the SVG wiki.

Jonas Pegerfalk