检查是否加载了多个图像

发布于 2024-09-05 15:56:43 字数 503 浏览 5 评论 0原文

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

我已在数组中声明它们,我需要一种方法来检查它们是否已同时加载,但我不知道如何执行此操作。

这是我的代码:

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
}

如果我有更多图像,我稍后将在开发中,这将是一种非常低效的方法检查他们全部。

我如何同时检查它们?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

暗藏城府 2024-09-12 15:56:43

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

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

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();
}
混浊又暗下来 2024-09-12 15:56:43

难道不能简单地使用循环并将相同的函数分配给所有加载吗?

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

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];
  }
})();
陈年往事 2024-09-12 15:56:43

使用当所有图像和外部资源加载时触发的window.onload

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

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

更多信息请点击此处。

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.

鲸落 2024-09-12 15:56:43

使用 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')
})

The solution with Promise would be:

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

标点 2024-09-12 15:56:43

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

然而,使用 jQuery(document).ready 也比原生 window.onload 效果更好。

您正在使用 Chrome,不是吗?

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?

时光磨忆 2024-09-12 15:56:43

for 循环 中的 onload 方法无法解决此任务,因为 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 循环在每次迭代后运行回调来更新/处理最新加载的图像值。这样您就不必等待只有在最大图像之后才加载较小图像的情况。

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

或者只是使用这种方法在所有图像加载后进行回调。

这完全取决于您想做什么。希望它会对某人有所帮助。

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.

撩动你心 2024-09-12 15:56:43

试试这个代码:

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

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文