仅在加载后在HTML5 Canvas中显示数百个微小图像 [英] Showing hundreds of tiny images in HTML5 Canvas only after load

查看:114
本文介绍了仅在加载后在HTML5 Canvas中显示数百个微小图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个画布和100个小图像,我想以网格形式添加到画布中。

I have a canvas and 100 tiny images that I want to add to my canvas in a grid-like formation.

我已经实现了这一点,但图像正在画布上一个接一个地绘制,有时候第40个位置的图像可能会在第10个位置的图像之前绘制。

I have already achieved this, but the images are being draw on the canvas one by one and sometimes the image at the 40th position might be drawn before the image at the 10th position.

这需要几秒钟的时间然后我得到了我想要的结果,但是我想知道如何才能在加载后显示图像?

It takes a couple of seconds and then I get my desired result, but I was wondering how I could show images only after they're loaded?

我知道还有其他类似问题的问题但是我已经阅读了所有这些并尝试了他们的解决方案但尚未成功。

I know there are other questions with a similar problem but I have read all of them and tried their solutions but have not succeeded yet.

我有这段代码在画布上的正确位置逐个绘制图像使用嵌套for循环:

I have this piece of code that draws the images one by one on the canvas at the right position using nested for loops:

for(...) {
  for(..) {
    add_image(source, row, column, width, height);
  }
}

现在 add_image 实际创建一个图像对象并绘制它 onload

Now add_image actually creates an image object and draws it onload

function add_image(...) {
  let image = new Image();
  image.src = source;

  image.onload = function() {
    context.drawImage(img, row, col, width, height);
  }
}

在这种情况下,最好的方法是什么首先加载所有图像并绘制它们?我尝试创建一个数组并用所有图像对象填充它,然后当所有图像都被加载时,我会运行for循环来绘制图像,但它不起作用,我没有看到控制台错误所以我是留下无能为力。

In this exact situation, what is the best way to load all the images first and the "draw" them? I tried creating an array and populating it with all the image objects, then when all the images were loaded I would run the for loop to draw the images, but it wouldn't work and I didn't see a console error so I was left clueless.

提前谢谢!

推荐答案

添加图像到数组并像你一样计算每个图像。在图像onload事件中减少计数器。当计数为零时,所有图像都已加载并可以绘制。

Add the images to an array and count each image as you do. In the image onload event decrease the counter. When the count is zero all the images have been loaded and can be drawn.

示例:

var images = [];
var loading = 0;
function add_image(url,xpos,ypos) {
  var image = new Image();
  image.src = url;
  images.push({
     image : image,
     xpos : xpos,
     ypos : ypos,
  });
  loading += 1;
  image.onload = function() {
      loading -= 1;
      if(loading === 0){
         drawImages(); // call function to draw all the images.
      }
  }
}
function drawImages(){
   for(var i = 0; i < images.length; i ++){
       // draw the image
       ctx.drawImage(images[i].image,images[i].xpos,images[i].ypos);
   }
}

这篇关于仅在加载后在HTML5 Canvas中显示数百个微小图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆