Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How intrinsic dimensions are computed for SVG images?

Tags:

html

svg

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>
like image 226
Yaroslav Admin Avatar asked Oct 15 '25 07:10

Yaroslav Admin


1 Answers

I believe Chrome starts from the values that would be given if you embedded something whose size could not be worked out.

Those values are 300 x 150px.

It then looks like it's applying the aspect ratio from the viewBox to the 150px width to generate a new height of 150 x 96 / 105 = 137.142px which I guess it rounds to 137px

like image 186
Robert Longson Avatar answered Oct 17 '25 13:10

Robert Longson