greenoldman
greenoldman

Reputation: 21072

How to get size ratio of SVG in reliable way?

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

Upvotes: 1

Views: 1739

Answers (3)

ludeq
ludeq

Reputation: 31

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

Upvotes: -1

Robert Longson
Robert Longson

Reputation: 124109

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.

Upvotes: 2

Vlas Bashynskyi
Vlas Bashynskyi

Reputation: 2013

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

}

Upvotes: 2

Related Questions