首页 > 解决方案 > svg - 嵌入 png 图像高度 null

问题描述

我想将 png 图像嵌入到 svg 容器中,但希望保持纵横比,所以我只在 png 元素中添加 width 属性。对于这种情况,如何在 javascript 中获取 png 图像的高度:

<!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>

此示例将输出如下:

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

我想读出身高值!

标签: javascripthtmlsvg

解决方案


如此处所述,getAttribute读取内容属性,而您没有设置。您可以使用以下命令读取 IDL 属性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>


推荐阅读