javascript - 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
我想读出身高值!
解决方案
如此处所述,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>
推荐阅读
- angular - Angular- Material tags are not working properly
- kedro - kedro nodes input accept kwargs?
- c# - Reading email of other user using Gmail API
- java - Spring boot jar doesnt pick property if the properties file are split up
- python - How to draw plus sign (+) into n*n numpy zero array
- python - Too many boolean expressions in if statement, how to fix that?
- eclipse - Spring Tool Suite 4.7.1 更新后的编辑器错误
- node.js - Mongoose schema validation not working while adding data
- javascript - Replacing every item at i with j value in an array with JavaScript
- python - Python - Selenium - 使用 WebDriverWait 在 html 中包含文本的 webscrape 表