angelblood_6x
angelblood_6x

Reputation: 29

Firefox svg rendering: how to get real g position?

I have a page with a svg loaded via object.

Then, I call a function that loads a div, using width, height, left and top of an internal g element

var cartina = document.getElementById(whatMap);
        var cartinaContext;         
        cartina.addEventListener("load",function(){
        cartinaContext = cartina.contentDocument;
        var el   = $("#mappaBase", cartinaContext)[0]; 
        var rect = el.getBoundingClientRect(); 
        var whatContainer = "#containerIcone"+whatMap;
        $(whatContainer).css("position", "absolute");
        $(whatContainer).width(rect.width);
        $(whatContainer).height(rect.height);
        $(whatContainer).css("left", rect.left);
        $(whatContainer).css("top", rect.top);
}

I'm using getBoundingClientRect(). I'm applying the div #containerIcone over the svg. In Chrome it works smoothly well. The problem is in Firefox: when I load the page, width and height are properly loaded but left and top are not. If I inspect the svg with Firefox, it appears that the g element is placed in a fixed position, while the rendered g element has another one (responsive to window dimensions and other elements position). Still, the g fixed element reacts well to window various sizes. The div is placed over the g element fixed inspect-position.

Inspecting the same element with Chrome reveals that the g element inspect box is drawed everytime where the g rendered element is.

How can I make this work in Firefox?

Upvotes: 0

Views: 657

Answers (1)

angelblood_6x
angelblood_6x

Reputation: 29

I found a solution, it's working cross-browser. Instead of positioning with .top and .left of the nested g element, I get width and height of nested element

var el   = $(nestedElement); 
var rect = el.getBoundingClientRect(); 

Then I get width and height of the parent svg element

var rectSvg = mysvg.getBoundingClientRect();

Then I subtract the el width and height from the svg ones, and divide results by 2. The final result is the white space the svg has inside it, top and left, used to center the rendered element el inside the svg element (used by browser to mantain aspect ratio). Then I apply those results as css top and left of my div containing icons - it will be positioned exactly over the g el element.

var leftSpace = (rectSvg.width - rect.width)/2;
var topSpace = (rectSvg.height - rect.height)/2;
$(myPositionedDiv).css("left", leftSpace);
$(myPositionedDiv).css("top", topSpace);

This manner, however Firefox positions the element despite of rendering, left and top are correctly calculated.

Upvotes: 0

Related Questions