在 JavaScript 中等待图像加载完成

Let*_*ren 4 html javascript canvas image

我正在使用 JavaScript 加载图像。像这样的东西:

images[0]=new Image();
images[0].onload=function(){loaded++;console.log(loaded)};
images[0].src="assets/img/image.png";
Run Code Online (Sandbox Code Playgroud)

当我查看日志时,我看到所有图像都加载得很好,因为“加载”变量的值随着每个加载的图像而增加。

但是我想停止执行任何进一步的操作,直到这个数量达到最大值,所以在设置图像后,我放置了一个 while 循环。

while(loaded<11){
    document.getElementById("test").innerHTML="Loading "+loaded+"/11";
    console.log(loaded);
}
//Some code here which should only run after everything has been loaded
//In other words: when the statement in the while cycle becomes false
Run Code Online (Sandbox Code Playgroud)

然而,我的浏览器只是崩溃了,因为 while 似乎陷入了无限循环。当我查看日志时,我看到“0”被写入了 1000 次,然后是从 1 到 11 的数字(这意味着图像实际上已加载,但 while 并不关心它,并且崩溃得更快比它可能发生)。

我相信我在这里尝试使用的方法不是解决这个问题的正确方法。

在加载站点所需的每个资产之前,如何将所有内容搁置?

Kim*_*att 9

使用 promises 和 async 函数,有一个很好的方法来等待所有图像加载完毕(没有回调,没有加载图像计数):

async function loadImages(imageUrlArray) {
    const promiseArray = []; // create an array for promises
    const imageArray = []; // array for the images

    for (let imageUrl of imageUrlArray) {

        promiseArray.push(new Promise(resolve => {

            const img = new Image();
            // if you don't need to do anything when the image loads,
            // then you can just write img.onload = resolve;

            img.onload = function() {
                // do stuff with the image if necessary

                // resolve the promise, indicating that the image has been loaded
                resolve();
            };

            img.src = imageUrl;
            imageArray.push(img);
        }));
    }

    await Promise.all(promiseArray); // wait for all the images to be loaded
    console.log("all images loaded");
    return imageArray;
}
Run Code Online (Sandbox Code Playgroud)

或者您可以等待加载单个图像:

async function loadImage(imageUrl) {
    let img;
    const imageLoadPromise = new Promise(resolve => {
        img = new Image();
        img.onload = resolve;
        img.src = imageUrl;
    });

    await imageLoadPromise;
    console.log("image loaded");
    return img;
}
Run Code Online (Sandbox Code Playgroud)

您可以像这样使用它(使用承诺链接):

loadImages(myImages).then(images => {
    // the loaded images are in the images array
})
Run Code Online (Sandbox Code Playgroud)

或者在异步函数中:

const images = await loadImages(myImages);
Run Code Online (Sandbox Code Playgroud)


Sai*_*ein 8

我个人讨厌使用 while()...我认为最简单的方法是使用事件侦听器。

var img = new Image;
img.addEventListener("load", function () {

//Img loaded

});
img.src= e.target.result;
Run Code Online (Sandbox Code Playgroud)