0

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.

myNewAccount
  • 578
  • 5
  • 17
  • 2
    `myImage.addEventListener('load', function() { /* your code here */ })` – connexo Jan 09 '21 at 02:23
  • @connexo Holy smokes I'm embarrassed. I didn't realize it worked the same on variables as it did on elements. – myNewAccount Jan 09 '21 at 02:25
  • Your variable holds a reference to an element, so why would it be any different? – connexo Jan 09 '21 at 02:27
  • @connexo Well it doesn't always have to make sense but you're right that makes perfect sense. And it 100% worked. – myNewAccount Jan 09 '21 at 02:29
  • Well think about it, how are you ever calling `addEventListener` on anything other than a reference to an element? Be it one stored in a variable, or one available at the moment of execution only like `document.createElement('img').addEventListener(...)`. – connexo Jan 09 '21 at 02:36
  • @connexo I understand `.addEventListener()` what I didn't realize was that `new Image()` was creating an image element. I just started using it today and thought it was some sort of image constructor, I wasn't really sure what for. Once I learned it was making an image element your answer made perfect sense. – myNewAccount Jan 09 '21 at 02:47

1 Answers1

4

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.

D M
  • 5,769
  • 4
  • 12
  • 27