Necto
Necto

Reputation: 2654

Wrong SVGSVGElement width in Firefox

On th following document:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/SVG/DTD/svg10.dtd">

<svg width = "100%"
 height = "100%"
 id="pic"
 version="1.1"
 style="background-color:blue"
 xml:space="preserve"
 xmlns="http://www.w3.org/2000/svg"
 xmlns:ev="http://www.w3.org/2001/xml-events"
 xmlns:xlink="http://www.w3.org/1999/xlink">

</svg>

I'm trying to get the width value of the root SVGSVGElement:

document.getElementById ("pic").width.baseVal.value

Chromium says: 969

Firefox says: 1

Sure value maybe a little implementation dependent, but (what indeed must be independent) when i try to get a converted value:

var w = evt.target.width.baseVal;
w.convertToSpecifiedUnits (5);
alert(w.valueInSpecifiedUnits);

chrome gives again 969, but Firefox' answer is 1.

I need this value to adjust some elements in my scripts, but they don't work in Firefox. How can i obtain the real value of width?

Upvotes: 1

Views: 734

Answers (3)

Robert Longson
Robert Longson

Reputation: 124059

From Firefox 33 onwards you will be able to use getBoundingClientRect to get the width/height you want. Firefox 33 will be released on 14th October 2014 but you could try a nightly right now if you want to.

Upvotes: 1

Sergio
Sergio

Reputation: 28837

This is the way I got it to give consistent values cross-browser:

This was the way I fixed it:

var heightComponents = ['height', 'paddingTop', 'paddingBottom', 'borderTopWidth', 'borderBottomWidth'],
    widthComponents = ['width', 'paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth'];

var svgCalculateSize = function (el) {

    var gCS = window.getComputedStyle(el), // using gCS because IE8- has no support for svg anyway
        bounds = {
            width: 0,
            height: 0
        };

    heightComponents.forEach(function (css) { 
        bounds.height += parseFloat(gCS[css]);
    });
    widthComponents.forEach(function (css) {
        bounds.width += parseFloat(gCS[css]);
    });
    return bounds;
};

Not very pretty, but works.

Upvotes: 1

Pete Kozak
Pete Kozak

Reputation: 623

2 years later this is still an issue..

I found a temporary solution:

var style = window.getComputedStyle(svg,null);
var svgWidth = style.getPropertyValue("width").slice(0, -2);  // "1240px" -> "1240"

but in my case this is very expensive and the browser gets super slow.. so, has anyone got a better solution?

I also tried to convert "the magic 1" into a pixel width following this article: https://developer.mozilla.org/en/docs/Web/API/SVGLength but no luck either..

Upvotes: 1

Related Questions