Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrieving the aspect ratio of an svg <image>

Tags:

javascript

svg

TLDR; given this svg element:

<image width="30" height="48" x="3.75" y="6" href="http://some/image.jpg">

How can I retrieve the image's actual height and width (seeing as it is defined in part by the image's aspect ratio).


I have a d3js script that draws a bunch of <rect>s and a bunch of <image>s. Now stuff is laid out so that the images fall inside the rects, as though the rects were borders. There is other stuff inside the rects too.

Now each of these images has it's own unique and special aspect ratio and this bothers me because it means each of the rects then has a different amount of blank space. This is untidy.

To avoid this I want to load the images then get the actual image dimensions and then adjust the positions and sizes of the surrounding goodies. The crux of the matter is getting the actual image sizes. How can I do this?

I've googled around a bit and spent some quality time with the debugging console to no avail. Just nothing comes up. I'll keep hunting but an answer would be really nice.

like image 420
Sheena Avatar asked Oct 26 '25 01:10

Sheena


2 Answers

First, set the width attribute only, keep height unspecified. Then, call the getBBox for the image element. Note that image box is available after it's properly rendered by the SVG

const image = parent.append('image').attr('xlink:href', url).attr('width', 100);
setTimeout(() => {
    const box = image.node().getBBox();
    const ratio = box.width / box.height;
}, 0);
like image 152
Michael Rovinsky Avatar answered Oct 27 '25 14:10

Michael Rovinsky


This is the best I can come up with. I would be surprised and horrified if there isn't an easier way. Anyway:

  1. add a normal html <img> element with a suitable src.
  2. use js to fetch the image height and width
  3. remove the extra html

Ugly but it works...

Here's some code:

var oImage = document.createElement("img");
oImage.setAttribute("src",sUrl);
document.body.appendChild(oImage);
var iWidth = oImage.width;
var iHeight = oImage.height;
oImage.remove();
like image 39
Sheena Avatar answered Oct 27 '25 15:10

Sheena