我对 Javascript 相当陌生,目前正在尝试以各种尺寸和位置显示图像。这意味着我必须先加载图像,然后才能访问宽度和高度等值。
现在,这就是我面临问题的地方。
我尝试依次加载图像,确保只有在完成一张图像后才会加载另一张图像。
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);
显然,这不会产生正确的结果。 for循环之后的Logs仍然是0,并且在for循环内的Logs之前打印。这意味着,程序不会等待图像完成。
接下来,我尝试了这个:
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);
这样做的效果更糟。该页面甚至没有首先加载,它似乎永远卡在 while 循环中。这是有道理的,因为我认为每次images[loaded].src
设置后,加载过程将重新开始,因此永远不会取得任何进展。
我发现的任何解决方案都包括 HTML 代码,其中图像是通过 document.querySelector() 从 HTML 加载的,但我无法使用它,或者对于我来说太复杂了,甚至无法像一个刚刚起步的人那样思考。我不需要完美的解决方案,现在我只需要可行的东西。事情不可能那么复杂,对吧?我只想加载一些图像。我真的被困在这里了。
这是另一个基于承诺的答案:
const images = [...document.querySelectorAll("div img")];
const proms=images.map(im=>new Promise(res=>
im.onload=()=>res([im.width,im.height])
))
// list all image widths and heights _after_ the images have loaded:
Promise.all(proms).then(data=>{
console.log("The images have loaded at last!\nHere are their dimensions (width,height):");
console.log(data);
})
// Everything is set up here.
// Except: the images don't have their `src` attributes yet!
// These are added now and the action will unfold:
images.forEach((im,i)=>im.src=`https://picsum.photos/id/${i+234}/200/100`);
<div><img><img></div>
上面的极简形式可能如下所示:
const images = [...document.querySelectorAll("div img")];
// list all image widths and heights _after_ the images have loaded:
Promise.all(images.map(im=>new Promise(resolve=>im.onload=resolve))).then(()=>{
console.log("The images have loaded at last!\nHere are their dimensions (width,height):");
console.log(images.map(im=>([im.width,im.height])));
})
// Now, trigger the action:
images.forEach((im,i)=>im.src=`https://picsum.photos/id/${i+234}/200/100`);
<div><img><img></div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)