Sheena
Sheena

Reputation: 16232

retrieving the aspect ratio of an svg <image>

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.

Upvotes: 4

Views: 1295

Answers (2)

Michael Rovinsky
Michael Rovinsky

Reputation: 7210

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);

Upvotes: 2

Sheena
Sheena

Reputation: 16232

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();

Upvotes: 1

Related Questions