Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the actual size of an embedded SVG element, if it's auto-resizing?

I set up an auto-resizing SVG that changes size based on the parent container while keeping the aspect ratio.

I want to center the SVG element in the parent container because the dimensions of the parent container doesn't necessary match the SVG's dimensions .

I created a fiddle to demonstrate what I mean: http://jsfiddle.net/lazthewiz/cXx46/

HTML

<DIV>
<SVG id=svg viewBox="0 0 160 90" preserveAspectRatio="xMinYMin">
...

CSS

DIV {
    width: 200px;
    height: 200px;    
}

SVG {
    width: 100%;
    height: 100%;
}

The width and height values returned by jQuery or found in the DOM are useless in this case. They either return zero, or the parent container's dimensions (depending on what browser you use).

Is there a way to get the actual dimensions of the embedded SVG either with jQuery or plain JS?

like image 860
Laszlo the Wiz Avatar asked Oct 01 '22 02:10

Laszlo the Wiz


2 Answers

I actually found the solution which is far less involved (but a bit hacky) than doing aspect ratio calculations.

The trick was that I created an invisible line (no stroke) from the top left corner to the bottom right corner of the SVG canvas. Then I got the actual screen dimensions of the bounding box of that line.

So with an example:

HTML

<SVG viewBox="0 0 160 90" ...>
   ...
   <line x1=0 y1=0 x2=160 y2=90 id=dimline />
</SVG>

JS

var width=$("#dimline")[0].getBoundingClientRect().width;
var height=$("#dimline")[0].getBoundingClientRect().height;

And here's a fiddle that works on FF, Chrome and IE: http://jsfiddle.net/lazthewiz/cXx46/5/

(In IE it adds a couple of pixels of what would be expected but that's not a big deal for centering purposes).

like image 65
Laszlo the Wiz Avatar answered Oct 03 '22 16:10

Laszlo the Wiz


I reckon so. Haven't tested with anything other than Google Chrome (33.0.1750.154 m). For your code/styles, I actually get the value of 200 and 112.5 (rather than 200x113)

var mImg = document.getElementById('svg');
var aspect = mImg.viewBox.baseVal.height / mImg.viewBox.baseVal.width;
var width = mImg.clientWidth;
var height = width * aspect;
var msg = '';
msg += 'width: ' + width;
msg += ', ';
msg += 'height: ' + height;
document.body.appendChild( document.createTextNode(msg) );

I suppose that this would fail if the image was tall, instead of wide - but I guess you could decide how to calculate the size correctly based on which dimension of the viewBox was larger - the width or the height.

like image 27
enhzflep Avatar answered Oct 03 '22 16:10

enhzflep