Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a SVG's aspect ratio? [duplicate]

Is there a way to get a loaded svg's aspect ratio? I want to be able to know the scaling that goes into the preserveAspectRatio property. The documentation states that for meet:

  • aspect ratio is preserved
  • the entire viewBox is visible within the viewport
  • the viewBox is scaled up as much as possible, while still meeting the other criteria

Is there a way to retrieve the aspect ratio that the property somehow knows in JS?

like image 504
poliu2s Avatar asked Oct 26 '25 10:10

poliu2s


1 Answers

It's fairly easy to get the viewBox's values like described in Phrogz' answer to "Obtaining an original SVG viewBox via javascript":

var svg = document.querySelector('svg');
var box = svg.viewBox.baseVal;

Getting the aspect ratio from that requires just simple math:

var aspectRatio = box.width / box.height;
like image 156
altocumulus Avatar answered Oct 28 '25 23:10

altocumulus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!