How intrinsic dimensions are computed for SVG images?

Viewed 1316

HTML 5 specifiction defines that:

The IDL attributes naturalWidth and naturalHeight must return the intrinsic width and height of the image, in CSS pixels, if the image is available, or else 0.

It's clear how intrinsic width and height for JPG, PNG, GIF are computed - they all have fixed dimensions in px. But I can't find how these dimensions are computed for SVG images.

I've made an experiment with arbitrary SVG image and it returns different values in different browsers:

  • Chrome - 137 x 150
  • Firefox - 0 x 0
  • Safari - returns dimensions of the DOM element instead of intrinsic dimensions

So is there any specification defining how it should behave? And why Chrome is returning these values? I can understand behavior implemented in Safari and Firefox, but Chrome is doing something interesting.

const width = document.getElementById('img').naturalWidth;
const height = document.getElementById('img').naturalHeight;

document.getElementById('result').innerText = `Width: ${width}\nHeight: ${height}`;
<img id="img" src="https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/android.svg">
<div id="result"></div>

2 Answers

You can create a new Image object without putting it into the DOM. Then the image will have the correct natural width.

var i = new Image();
i.src = document.getElementById('img').src;
i.naturalWidth
Related