Checking for multiple images loaded

妖精的绣舞 提交于 2020-01-13 08:18:30

问题


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 them inside an array, I need a way of checking if they have all loaded at the same time but I am not sure how to do this.

Here is my code:

var color = new Array();
color[0] = new Image();
color[0].src = "green.png";
color[1] = new Image();
color[1].src = "blue.png";

Currently to check if the images have loaded, I would have to do it one by one like so:

color[0].onload = function(){
//code here
}
color[1].onload = function(){
//code here
}

If I had a lot more images, Which I will later in in development, This would be a really inefficient way of checking them all.

How would I check them all at the same time?


回答1:


A hackish way to do it is add the JS command in another file and place it in the footer. This way it loads last.

However, using jQuery(document).ready also works better than the native window.onload.

You are using Chrome aren't you?




回答2:


If you want to call a function when all the images are loaded, You can try following, it worked for me

var imageCount = images.length;
var imagesLoaded = 0;

for(var i=0; i<imageCount; i++){
    images[i].onload = function(){
        imagesLoaded++;
        if(imagesLoaded == imageCount){
            allLoaded();
        }
    }
}

function allLoaded(){
    drawImages();
}



回答3:


Can't you simply use a loop and assign the same function to all onloads?

var myImages = ["green.png", "blue.png"];

(function() {
  var imageCount = myImages.length;
  var loadedCount = 0, errorCount = 0;

  var checkAllLoaded = function() {
    if (loadedCount + errorCount == imageCount ) {
       // do what you need to do.
    }
  };

  var onload = function() {
    loadedCount++;
    checkAllLoaded();
  }, onerror = function() {
    errorCount++;
    checkAllLoaded();
  };   

  for (var i = 0; i < imageCount; i++) {
    var img = new Image();
    img.onload = onload; 
    img.onerror = onerror;
    img.src = myImages[i];
  }
})();



回答4:


Use the window.onload which fires when all images/frames and external resources are loaded:

window.onload = function(){
  // your code here........
};

So, you can safely put your image-related code in window.onload because by the time all images have already loaded.

More information here.




回答5:


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.




回答6:


try this code:

<div class="image-wrap" data-id="2">
<img src="https://www.hd-wallpapersdownload.com/script/bulk-upload/desktop-free-peacock-feather-images-dowload.jpg" class="img-load" data-id="1">
<i class="fa fa-spinner fa-spin loader-2" style="font-size:24px"></i>
</div>

<div class="image-wrap" data-id="3">
<img src="http://diagramcenter.org/wp-content/uploads/2016/03/image.png" class="img-load" data-id="1">
<i class="fa fa-spinner fa-spin loader-3" style="font-size:24px"></i>
</div>
<script type="text/javascript">
    jQuery(document).ready(function(){
        var allImages = jQuery(".img-load").length;
        jQuery(".img-load").each(function(){
            var image = jQuery(this);
            jQuery('<img />').attr('src', image.attr('src')).one("load",function(){
                var dataid = image.parent().attr('data-id');
                console.log(dataid);
                 console.log('load');
            });
        });

    });

</script>


来源:https://stackoverflow.com/questions/3032299/checking-for-multiple-images-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!