0

I'm working with react and I'm trying to get the height and width from an image from which I only have the url. This is what I have so far:

const testImg = new Image();
let a; let b;

testImg.addEventListener("load", function(){
console.log("1. Properties " + testImg.width + " " + testImg.height);
a = testImg.width;
b = testImg.height;
});

testImg.src = thumbUrl;

console.log("2. Properties " + testImg.width + " " + testImg.height);
console.log("3. Properties " + a + " " + b);

The output of the first "properties" log is correct (336 & 223 pixels). The output of the second is 0 & 0 and the output of the third is undefined & undefined.

I have tried puting the "testImg.src = thumbUrl" line before the onload function and the outputs are the same. I need to use these values outside that function. Also have tried using the decode function.

If you have any other approach or a solution for this I'd appreciate that very much.

lufesome
  • 11
  • 5
  • https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call - this one is about AJAX requests, but the underlying problem of asynchronicity is the same here. – CBroe Aug 31 '21 at 14:42
  • The better approach is to simulate an image loading with fixed width/height then after `loaded` update the width/height. The Event is trigger after 2. and 3. – Patfreeze Aug 31 '21 at 14:47
  • Pure JS: https://jsfiddle.net/3cnbh7jq/ – Patfreeze Aug 31 '21 at 14:55
  • Is there anyway I can work with this, without the using the DOM part? Something like throw the loading of the image in a async function? I tried that but it seems that I didnt do it properly – lufesome Aug 31 '21 at 15:15
  • can't you just run the code that needs to use those dimensions in the onload? – Pete Aug 31 '21 at 15:42

0 Answers0