SVG 中 <image> 標籤引用外部圖片,如何在圖片加載完成後獲取其原始寬高並設置給 SVG 元素?
利用 JavaScript Image 對象預加載,onload 回調中讀取 width/height:
var img = new Image();
img.onload = function() {
// 此處 this.width / this.height 即為原始尺寸
// 設置 SVG image 元素的 width/height 屬性
document.getElementById('svgImg').setAttribute('width', this.width);
document.getElementById('svgImg').setAttribute('height', this.height);
};
img.src = 'https://example.com/image.png'; // 觸發加載
注意:必須在 onload 後設置,否則圖片未加載完成尺寸為 0。