How do I make an image load synchronously?

后端 未结 5 1961
暖寄归人
暖寄归人 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:04

    I wrapped it into function, and it worked!

    for (var i = 0, i < asset.length; i++) {
    
        var img = new Image();
        img.src = "file:///" + folder + "/" + asset[i].name;
    
        getWdrp(img);
    
        function getWdrp (img) {
            img.onload = function(){
                // work with the image file
            }
        }
    }
    

    This is an example that worked for me, because before, when I was processing the image without wrapping in the function, it would work async, now it is async.

提交回复
热议问题