I've run into this problem a lot with D3. A lot of the time I like to overlay HTML objects over my SVG.
My current strategy is creating an empty DIV next to the SVG element called .html-overlay. I position it according to the internal padding I set in the SVG for my main graphic (ex: 20px). Then I use the following function (with jQuery) to figure out where the HTML element should go:
//element is the object returned by D3 .append() var getOffset: function(element) { var $element = $(element[0][0]); return { left: $element.offset().left - $('.html-overlay').offset().left, top: $element.offset().top - $('.html-overlay').offset().top }; }
I wonder, there MUST be some internal (non-jQuery dependant) way to quickly get an element's offset. It's very useful (especially after an elements goes through multiple translations, rotations, scales, etc.)
It would also be great to have functions for figuring out the offset of the "center" of an element, the topmost point of element, bottommost, leftmost, rightmost, etc.
NOTE:
The getBoundingClientRect() doesn't give the correct numbers for some reason:
var $element = $(element[0][0]); console.log($element.offset(), element[0][0].getBoundingClientRect()) Object left: 328 top: 248.8333282470703 __proto__: Object ClientRect bottom: 376.83331298828125 height: 139.99998474121094 left: 328 right: 478 top: 236.8333282470703 width: 150
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.
jQuery . offset() will get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.
The offsetTop property returns the top position (in pixels) relative to the parent. The returned value includes: the top position, and margin of the element. the top padding, scrollbar and border of the parent.
When it comes to the positioning of SVG elements like “<rect>” or “<circle>”, there's already a big difference to HTML regarding the syntax. While HTML elements are placed via CSS attributes “left” and “top”, SVG elements can only be placed via “x” and “y” attributes (“cx” and “cy” attributes for circles).
did you try
var xywh =element[0][0].getBoundingClientRect();
seems to have everything in it? (original soution is in this post)
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