Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding Offset Position of SVG Element

Tags:

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 
like image 634
Toli Avatar asked Oct 23 '12 23:10

Toli


People also ask

How do I find the coordinates of a SVG element?

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.

How do you get the offset of an element?

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.

What is offset() top?

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.

How to position SVgs?

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).


1 Answers

did you try

var xywh =element[0][0].getBoundingClientRect(); 

seems to have everything in it? (original soution is in this post)

like image 135
Asain Kujovic Avatar answered Oct 09 '22 04:10

Asain Kujovic