I'm fairly new to Javascript and I'm currently trying to display images at various sizes and positions. This means I have to load the images first, before I can access values like width and height. Now, here's where I'm facing problems.
I tried loading the images one after another, making sure another image would only be loaded when one image is completed.
const a = new Image();
const b = new Image();
const images = [
a,
b
];
const imageLinks = [
'a.png',
'b.png'
];
let loaded = 0;
for (let i = 0; i < images.length; i++) {
images[i].onload = function() {
console.log(images[i].width);
console.log(images[i].height);
loaded++;
}
images[i].src = imageLinks[i];
}
console.log(images[0].width);
console.log(images[0].height);
Obviously, this doesn't produce the correct result. The Logs after the for-loop are still 0 and are printed before the Logs inside the for-loop. That means, the program doesn't wait for the images to finish.
Next, I tried this:
let loaded = 0;
while (loaded < images.length) {
images[loaded].onload = function() {
console.log(images[loaded].width);
console.log(images[loaded].height);
loaded++;
}
images[loaded].src = imageLinks[loaded];
}
console.log(images[0].width);
console.log(images[0].height);
This does even worse. The page doesn't even load in the first place, it seems to be stuck forever in the while-loop. This makes sense because I reckon that everytime images[loaded].src
is set, the loading process starts over, thus never making any progress.
Any solutions I've found include HTML-code, where images are loaded from HTML via document.querySelector(), which I cannot use, or are way too complicated for me to even try to wrap my head around as someone who's just starting out. I don't need a perfect solution, for now I just need something that works. It can't be that complicated, right? I just want to load a few images. I'm really stuck here.