[英]React synthetic event returned from onLoad() of <image> element inside <svg> does not have naturalWidth or naturalHeight properties
I am using ReactJS.我正在使用 ReactJS。 My aim is to trigger some events when an image loads inside an SVG element.
我的目标是在 SVG 元素内加载图像时触发一些事件。
Without SVG element, this code below works as expected -如果没有 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>
)
However, this code does not work as expected -但是,此代码无法按预期工作-
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>
)
I have tried reading in several places.我曾尝试在几个地方阅读。 Its not clear why
<image>
is different from <img>
for onLoad()
synthetic event in react.不清楚为什么
<image>
与<img>
的onLoad()
合成事件在反应中不同。
Unlike HTMLImageElement , the SVGImageElement interface doesn't expose a naturalWidth
or naturalHeight
properties, nor any ways to retrieve the intrinsic size of the inner image by the way.与HTMLImageElement不同, SVGImageElement接口不公开
naturalWidth
或naturalHeight
属性,也没有任何方法来检索内部图像的固有大小。
If you want to get it, the easiest would be to load the image again in an HTML <img>
, an alternative would be to create an ImageBitmap from the <image>
but not all browsers do support it.如果你想得到它,最简单的方法是在 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.