Spadar Shut
Spadar Shut

Reputation: 15817

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

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.

Upvotes: 17

Views: 21449

Answers (2)

KeatsKelleher
KeatsKelleher

Reputation: 10191

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.

Upvotes: 39

jball
jball

Reputation: 25024

SVGs are scalable vector graphics, and thus can have any arbitrary height and width. Only the ratio is fixed by the format.

Upvotes: -3

Related Questions