[英]naturalWidth and naturalHeight returns 0 using onload event
[英]React synthetic event returned from onLoad() of <image> element inside <svg> does not have naturalWidth or naturalHeight properties
我正在使用 ReactJS。 我的目标是在 SVG 元素内加载图像时触发一些事件。
如果没有 SVG 元素,下面的代码将按预期工作-
function onImageLoad(event) {
console.log("Event triggered from <img> element", event);
// AS EXPECTED : Event object has natural width and natural height
}
return (
<div>
<img src={imageName} onLoad={ (event) => onImageLoad(event) }/>
</div>
)
但是,此代码无法按预期工作-
function onImageLoad(event) {
console.log("Event triggered from <image> element", event);
// UNEXPECTED : Event object does not have natural width or natural height
}
return (
<div>
<svg>
<image href={imageName} onLoad={ (event) => onImageLoad(event) }/>
</svg>
</div>
)
我曾尝试在几个地方阅读。 不清楚为什么<image>
与<img>
的onLoad()
合成事件在反应中不同。
与HTMLImageElement不同, SVGImageElement接口不公开naturalWidth
或naturalHeight
属性,也没有任何方法来检索内部图像的固有大小。
如果你想得到它,最简单的方法是在 HTML <img>
中再次加载图像,另一种方法是从<image>
创建ImageBitmap ,但并非所有浏览器都支持它。
const svgImg = document.querySelector("image"); const getSVGImageSize = async (src) => { const img = new Image(); img.src = src.href.baseVal; await img.decode(); const { width, height } = img; return { width, height }; }; getSVGImageSize(svgImg) .then(({ width, height }) => console.log("from HTMLImageElement", { width, height })) // alternative using createImageBitmap, // not supported in Safari svgImg.addEventListener("load", e => createImageBitmap(svgImg) .then(({ width, height }) => console.log("fom ImageBitmap", { width, height })) .catch(console.error) );
<svg> <image href="https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png"/> </svg>
您需要传递 event.currentTarget,而不是事件本身
<image href={imageName} onLoad={ (event) => onImageLoad(event.currentTarget) }/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.