Checking for multiple images loaded

后端 未结 7 2203
死守一世寂寞
死守一世寂寞 2021-02-20 09:26

I\'m using the canvas feature of html5. I\'ve got some images to draw on the canvas and I need to check that they have all loaded before I can use them.

I have declared

7条回答
  •  一个人的身影
    2021-02-20 09:41

    Just onload method in for loop does not solve this task, since onload method is executing asynchronously in the loop. So that larger images in the middle of a loop may be skipped in case if you have some sort of callback just for the last image in the loop.

    You can use Async Await to chain the loop to track image loading synchronously.

    function loadEachImage(value) {
       return new Promise((resolve) => {
          var thumb_img = new Image();
          thumb_img.src = value;
          thumb_img.onload = function () {
             console.log(value);
             resolve(value); // Can be image width or height values here
          }
       });
    }
    
    function loadImages() {
       let i;
       let promises = [];
    
       $('.article-thumb img').each(function(i) {
          promises.push(loadEachImage( $(this).attr('src') ));
       });
    
       Promise.all(promises)
          .then((results) => {
              console.log("images loaded:", results); // As a `results` you can get values of all images and process it
          })
          .catch((e) => {
             // Handle errors here
          });
    }
    
    loadImages();
    

    But the disadvantage of this method that it increases loading time since all images are loading synchronously.


    Also you can use simple for loop and run callback after each iteration to update/process latest loaded image value. So that you do not have to wait when smaller images are loaded only after the largest.

    var article_thumb_h = [];
    var article_thumb_min_h = 0;
    
    $('.article-thumb img').each(function(i) {
       var thumb_img = new Image();
       thumb_img.src = $(this).attr('src');
       thumb_img.onload = function () {
          article_thumb_h.push( this.height ); // Push height of image whatever is loaded
          article_thumb_min_h = Math.min.apply(null, article_thumb_h); // Get min height from array
          $('.article-thumb img').height( article_thumb_min_h ); // Update height for all images asynchronously
       }
    });
    

    Or just use this approach to make a callback after all images are loaded.

    It all depends on what you want to do. Hope it will help to somebody.

提交回复
热议问题