svg - embed png image height null

Viewed 76

I would like to embed a png image into svg container but wish to keep aspect ratio, so I only add width property in png element. how can I get the height of the png image in javascript for this case:

<!DOCTYPE html>
<html>
<head>
<style>
#img {
  outline: 1px solid red;
}
</style>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg" id="mysvg" viewBox="0 0 800 400" preserveAspectRatio="xMidYMid meet">
  <title>SVG demo</title>
  <desc>example SVG</desc>
  <image id="img" xlink:href="input.png" width="500" x="100" y="100" />
</svg>
<script>
// initialize
const
  svg = document.getElementById('mysvg'),
  img = document.getElementById('img');

  img.onload = function() {
    console.log("x:",img.getAttribute('x'));
    console.log("y:",img.getAttribute('y'));
    console.log("width:",img.getAttribute('width'));
    console.log("height:",img.getAttribute('height'));
  }
</script>
</body>
</html>

This example will output as below:

x:100
y:100
width:500
height:null

I would like to read out the height value!

2 Answers

As explained here, getAttribute reads content attributes, and you are setting none. You can read the IDL attribute with window.getComputedStyle:

// initialize
const
  svg = document.getElementById('mysvg'),
  img = document.getElementById('img');

  img.onload = function() {
    console.log("x:",img.getAttribute('x'));
    console.log("y:",img.getAttribute('y'));
    console.log("width:",img.getAttribute('width'));
    console.log("height:",window.getComputedStyle(img).height);
  }
<svg xmlns="http://www.w3.org/2000/svg" id="mysvg" viewBox="0 0 800 400" preserveAspectRatio="xMidYMid meet">
  <title>SVG demo</title>
  <desc>example SVG</desc>
  <image id="img" xlink:href="https://i.stack.imgur.com/0Dwrn.png" width="500" x="100" y="100" />
</svg>

Her's an approach that should work in all modern-ish browsers.

let img = document.getElementById('img');
// Wait for SVG <image> element to finish loading
img.onload = function() {
  // Create an HTML <img> element with the same URL so we can get
  // the image's naturalWidth and naturalHeight
  let tmp = new Image();
  tmp.onload = function () {
    // Calculate the final <image> height using the width and
    // the image's natural (actual) width and height
    w = img.width.baseVal.value;
    h = w * tmp.naturalHeight / tmp.naturalWidth;
    console.log('width='+w+' height='+h);
  }
  tmp.src = img.getAttribute('xlink:href');
}
<svg viewBox="0 0 800 400" preserveAspectRatio="xMidYMid meet">
  <image id="img" xlink:href="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/00_1373_Milford_Sound_-New_Zealand.jpg/640px-00_1373_Milford_Sound_-New_Zealand.jpg" width="500" x="100" y="100" />
</svg>

Related