1

I have svg element already loaded, and I would like to get not width or height, but actually a ratio. So for example 1 would mean square. 2 could mean (width/height) that the width is two times as height. And so on.

I've googled yet didn't find anything reliable (or working). So far I found out of myself that I could access width and height properties, then animVal, and then value. So the ratio would be:

ratio = svg.width.animVal.value / svg.height.animVal.value;

The problem is animVal holds also unitType, and what do to if unit type for width is different than for height? Well, could they be different?


I created SVG with Inkscape, and this is how I load SVG in JS:

$.get(svg_url, function(data) {
    // Get the SVG tag, ignore the rest
    svg = $(data).find('svg')
            .attr('id', 'SVG')
            // Remove any invalid XML tags as per http://validator.w3.org
           .removeAttr('xmlns:a')
           [0];

    on_load();
}, 'xml');

The code comes from How to change color of SVG image using CSS (jQuery SVG image replacement)?. What I have later on is svg element.

This is not the question how to load SVG, or what to do with cross-domain issue. SVG loads fine, it is the same domain as the script (my disk).

Community
  • 1
  • 1
greenoldman
  • 16,895
  • 26
  • 119
  • 185

3 Answers3

2

You can also try naturalHeight and naturalWidth properties of image element in JavaScript. For Example:

var img = document.createElement('img');
img.src = 'example.svg';
img.onload = function(){

    alert( img.naturalHeight/img.naturalWidth );

}
Vlas Bashynskyi
  • 1,886
  • 2
  • 16
  • 25
2

The value field converts the units to user units (i.e. unitless) so whatever units you use it will just work.

If for some reason you wanted the value in the supplied units then you'd write animVal.valueInSpecifiedUnits instead.

Robert Longson
  • 118,664
  • 26
  • 252
  • 242
-1

it worked for me (after appending content to html)

console.log('SVG size: ' + svg.offsetWidth + '×' + svg.offsetHeight);
$('#svgCont').append(svg);
console.log('SVG size: ' + svg.offsetWidth + '×' + svg.offsetHeight);
ludeq
  • 31
  • 2
  • offsetWidth and offsetHeight are [properties of html elements and not SVG elements](http://www.w3.org/TR/cssom-view/#extensions-to-the-htmlelement-interface). You are relying on a Chrome bug for this to work. – Robert Longson Aug 12 '15 at 10:40