JavaScript waiting until an image is fully loaded before continuing script

前端 未结 3 1311
太阳男子
太阳男子 2021-01-17 09:56

I\'ve been looking around a lot of JavaScript answers but I haven\'t found one that really answers my problem yet. What I\'m trying to do is load an image, grab the pixel da

3条回答
  •  野的像风
    2021-01-17 10:54

    Maybe this will help:

    currentimage.onload = function(e){
        // code, run after image load
    }
    

    If it is necessary to wait for the image to load, the following code will load the next image (currentIndex is your "img" variable):

    var loadImages = function(imageURLarray, currentIndex){
        if (imageURLarray.length == 0 || imageURLarray.length == currentIndex) return false;
        if (typeof currentIndex == 'undefined'){
           currentIndex = 0;
        }
        // your top code
        currentimage.onload = function(e){
            // code, run after image load
            loadImages(imageURLArray, currentIndex++);
        }
    }
    

    Instead of a "for" loop, use for example this function:

    loadImages(imageURLarray);
    

提交回复
热议问题