[英]Using JS is it possible to detect when new Image().src has loaded the image it references into memory?
Background: I'm trying to get the dimensions of an image.背景:我正在尝试获取图像的尺寸。
This block successfully creates a new image and assigns it a graphic.该块成功地创建了一个新图像并为其分配了一个图形。 Unfortunately this doesn't happen instantly.不幸的是,这不会立即发生。 When I attempt to get height with naturalHeight
it returns 0.当我尝试使用naturalHeight
获取高度时,它返回 0。
let myImage = new Image();
myImage.src = 'images/example.png';
let dimension = myImage.naturalHeight;
alert(dimension); // 0
However if I delay this action with setTimeout()
it gives the browser time to load it into memory and it returns the height.但是,如果我使用setTimeout()
延迟此操作,它会给浏览器时间将其加载到 memory 并返回高度。
setTimeout(function() {
let dimension = myImage.naturalHeight;
alert(dimension); // 479
}, 1000);
Question: Is there a way to detect if the image reference has been fully loaded into memory?问题:有没有办法检测图像参考是否已完全加载到 memory 中? This way I can grab naturalHeight
after I know the referenced image is loaded.这样我就可以在知道引用的图像已加载后获取naturalHeight
。
You can listen to the onload
event for the element.您可以监听元素的onload
事件。
let myImage = new Image();
// Be sure to add the event listener before
// changing the image's source attribute.
myImage.onload = function() {
let dimension = myImage.naturalHeight;
alert(dimension);
};
myImage.src = 'images/example.png';
More information in this answer .此答案中的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.