How do I make an image load synchronously?

后端 未结 5 1965
暖寄归人
暖寄归人 2020-12-06 10:21

I want to create an object that has an image property, but I want the contstructor to finish running only once the image is loaded. Or to describe this with code:

         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-06 11:12

    There is a non-evil way to load images in Javascript synchronously.

    loadImage = async img => {
        return new Promise((resolve, reject) => {
            img.onload = async () => {
                console.log("Image Loaded");
                resolve(true);
            };
        });
    };
    

    Call it with await anywhere. like this

    for(let i=0;i

    It will load all images one by one.

    Note: Calling function must be async to use await

提交回复
热议问题