javascript - 如何在 SVG 中获取光栅图像的原始尺寸?
问题描述
在 HTML 中,可以使用naturalHeight
和naturalWidth
属性知道图像的原始尺寸。例如:
<img
src="img.png"
onload="console.log({width:this.naturalWidth, height:this.naturalHeight});"
/>
但是image
SVG 中的元素没有这些属性。例如,以下代码undefined
为这两个属性返回:
<svg xmlns="http://www.w3.org/2000/svg">
<image
xlink:href="img.png"
onload="console.log({width:this.naturalWidth, height:this.naturalHeight});"
/>
</svg>
现在,我通过使用构造函数将图像加载到img
HTML 元素中的函数解决了这个问题:Image()
getRasterSize("img.png", function(size) {
console.log(size);
});
function getRasterSize(rasterURL, callback) {
var newImg = new Image();
newImg.src = rasterURL;
newImg.onload = function() {
var rasterSize = {
width: newImg.naturalWidth,
height: newImg.naturalHeight
};
if (typeof callback !== "undefined") callback(rasterSize);
};
}
但我想知道是否可以直接从 SVGimage
元素获取图像的原始尺寸,而无需先将图像加载到img
HTML 元素中。
解决方案
推荐阅读
- jquery - 尝试用 if else 语句替换计算时出现 NaN 错误?
- ios - Swift 4:自定义自动更正字典
- azure-web-app-service - 将 Azure 上的 Web 应用程序从美国区域迁移到印度数据中心
- c# - 如何快速执行和运行数百万个单元测试?
- c# - 检查字符串是否在文件中,如果是,则替换包含该字符串的特定行
- apache-spark - Spark:有没有办法在分布的每台本地机器上使用资源?
- ios - 在 didset 之后对象值不会改变
- databricks - Spark Streaming Notebook x 小时
- powershell - 从各种名称列表中获取 SamAccountName
- python - Python如何添加多个列表的总和