检查是否已加载多张图像

时间:2010-06-13 12:59:14

标签: javascript image canvas onload

我正在使用html5的画布功能。我在画布上画了一些图像,我需要检查它们是否已经全部加载才能使用它们。

我已将它们声明为数组,我需要一种方法来检查它们是否同时加载但我不知道该怎么做。

这是我的代码:

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

目前要检查图像是否已加载,我必须逐一进行,如下所示:

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

如果我有更多的图像,我将在后面进行开发,这将是一种非常低效的检查方式。

我如何同时检查所有这些?

7 个答案:

答案 0 :(得分:25)

如果你想在加载所有图像时调用一个函数,你可以尝试下面,它对我有用

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();
}

答案 1 :(得分:10)

你不能简单地使用循环并为所有onload分配相同的功能吗?

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];
  }
})();

答案 2 :(得分:3)

使用在加载所有 图片 /框架和外部资源时触发的window.onload

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

因此,您可以安全地将与图像相关的代码放在window.onload中,因为所有图片都已加载。

<强> More information here.

答案 3 :(得分:2)

执行此操作的一种hackish方法是将JS命令添加到另一个文件中并将其放在页脚中。这样它最后加载。

但是,使用jQuery(document).ready也比本机window.onload更好。

你使用Chrome不是吗?

答案 4 :(得分:1)

onload中的for loop方法不能解决此任务,因为onload方法在循环中异步执行。因此,如果您仅对循环中的最后一张图像进行某种回调,则可以跳过循环中间的较大图像。

您可以使用Async Await链接循环以同步跟踪图像加载。

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();

但是这种方法的缺点是由于所有图像都是同步加载的,因此增加了加载时间。


您还可以使用简单的for loop并在每次迭代之后运行回调 来更新/处理最新加载的图像值。这样一来,当仅在最大的图像之后才加载较小的图像时,您不必等待。

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
   }
});

或者在所有图像加载完毕后使用this approach进行回调。

这完全取决于您想做什么。希望对别人有帮助。

答案 5 :(得分:1)

使用Promise的解决方案是:

const images = [new Image(), new Image()]
for (const image of images) {
  image.src = 'https://picsum.photos/200'
}

function imageIsLoaded(image) {
  return new Promise(resolve => {
    image.onload = () => resolve()
    image.onerror = () => resolve()
  })
}

Promise.all(images.map(imageIsLoaded)).then(() => {
  alert('All images are loaded')
})

答案 6 :(得分:0)

尝试此代码:

<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>