首页 > 解决方案 > 如何在 SVG 中获取光栅图像的原始尺寸?

问题描述

在 HTML 中,可以使用naturalHeightnaturalWidth属性知道图像的原始尺寸。例如:

<img
    src="img.png"
    onload="console.log({width:this.naturalWidth, height:this.naturalHeight});"
/>

但是imageSVG 中的元素没有这些属性。例如,以下代码undefined为这两个属性返回:

<svg xmlns="http://www.w3.org/2000/svg">
    <image
        xlink:href="img.png"
        onload="console.log({width:this.naturalWidth, height:this.naturalHeight});"
    />
</svg>

现在,我通过使用构造函数将图像加载到imgHTML 元素中的函数解决了这个问题: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元素获取图像的原始尺寸,而无需先将图像加载到imgHTML 元素中。

标签: javascriptimagesvg

解决方案


推荐阅读