Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get svg graphics size when width/height attributes on <svg> are not set

Tags:

javascript

svg

So how to get the size of an SVG file with javascript when width and height are not set on the svg element? The svg is a string, but could be made a DOM if necessary.

like image 249
Spadar Shut Avatar asked Dec 29 '09 20:12

Spadar Shut


People also ask

How check SVG width and height?

To get width and height of SVG element with JavaScript, we can use the getBoundingClientRect method. const el = document. getElementById("yourElement"); const rect = el.

How do I change SVG render size?

Add viewBox="0 0 640 480" and set width="320" height="240" to the <svg> element to scale the SVG. you can go crazy on the width and height and control the aspect ratio with the preserveApsectRatio attribute.

Does SVG have size?

SVG's exported from Illustrator CC are 'responsive' by default, in other words there is no height or width attributes, no dimensions. This can be great, but sometimes you may want to force dimensions. Say for example you want to use an SVG for a logo on your website, but you want it to be a set size.


1 Answers

You can use the getBBox() method of the SVGElement object. It tells you the width and height, x, and y offset in pixels without taking into account the scaling of the element.

document.getElementById('myelem').getBBox().width  
document.getElementById('myelem').getBBox().height

are what you're looking for, I think.

EDIT:

  1. I've recently also learned that the little known getBoundingClientRect() works as well! You can also do: var el = document.getElementById('myelem'); var mywidth = el.getBoundingClientRect().width;

  2. Keep in mind that there is a difference between getBBox and getBoundingClientRect. getBBox gets the initial dimensions - getBoundingClientRect also respects the transformations done with scale etc.

like image 154
KeatsKelleher Avatar answered Oct 19 '22 07:10

KeatsKelleher