简体   繁体   中英

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.

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(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? This way I can grab naturalHeight after I know the referenced image is loaded.

You can listen to the onload event for the element.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM