I want to display an overlay (html div) when a user clicks on an element in an SVG diagram. To visualize the problem I'm having, suppose that the SVG image has a horizontal row of 6 elements. At the click event, I get the element's coordinates and use them to display the overlay next to it. The problem is that as I click the elements from left to right, I notice that the horizontal offset between the element and the overlay keeps getting smaller. That is, the 6th element displays the overlay much closer to it than the first element. This happens in both Chrome and FF, and it's an issue because sometime the overlay covers the element itself.
At first I was using JQuery's position() property, which didn't exhibit the behavior that I described above, but it returned very different values in Chrome and Firefox, plus it is not officially supported by JQuery on svg elements. So I tried with DOM's standard offsetLeft and offsetTop, as well as svg's x.animVal.value property and various libraries that I found on the web, but they all have the same erratic offset problem. I presume that this happens because the svg image is scaled, so I'm looking for I way to just get an svg's element position relative to the actual html document which contains it. Is there a way to do this?
The correct approach is to use element. getBoundingClientRect() : var rect = element. getBoundingClientRect(); console.
The element. getBoundingClientRect() method will return the proper coordinates of an element relative to the viewport regardless of whether the svg has been scaled and/or translated.
We can use the getBoundingClientRect method to get an element's position relative to its viewport. We get the div with querySelector . Then we call getBoundingClientRect on it to get an object with the top and left properties. top has the position relative to the top of the viewport.
For all elements, SVG uses a coordinate system or grid system similar to the one used by canvas (and by a whole lot of other computer drawing routines). That is, the top left corner of the document is considered to be the point (0,0), or point of origin.
In case you haven't worked something out since March (and for anyone else having this problem), try getBoundingClientRect()
on your SVG node.
Returns a ClientRect
object that gives you top, bottom, left, right, width, and height relative to the document. Was able to use this to position Twitter Bootstrap popovers (divs) next to SVG rects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With