【问题标题】:HTML 5 Canvas - Dynamically include multiple images in canvasHTML 5 Canvas - 在画布中动态包含多个图像
【发布时间】:2012-09-26 23:36:12
【问题描述】:

我需要在canvas 中包含多个图像。我想通过for-loop动态加载它们。

我尝试了很多,但在最好的情况下只显示最后一张图片。我检查了这个tread,但我仍然只得到最后一张图片。

为了解释,这是我最新的代码(基本上是另一篇文章的代码):

 for (var i = 0; i <= max; i++)
{
    thisWidth = 250;
    thisHeight = 0;
    imgSrc = "photo_"+i+".jpg";
    letterImg = new Image();
    letterImg.onload = function() {
        context.drawImage(letterImg,thisWidth*i,thisHeight);
    }
    letterImg.src = imgSrc;
}

有什么想法吗?

【问题讨论】:

  • Ummm,letterImg onload() 可以持有多个函数指针吗?
  • 不知道...我怎样才能避免这种情况?
  • @thatidiotguy 你只能有一个.onload,但在这种情况下,它每次都被放在不同的元素上,所以没关系。如果您想在一个元素上使用多个,我认为您可以使用addEventListener('load', ...)
  • 这不是问题,@thatidiotguy 和 Alnitak。

标签: javascript image html canvas


【解决方案1】:

问题是onload 事件异步发生,到那时循环变量已经是最后一个值。 您可以使用闭包来修复它:

for (var i = 0; i <= max; i++)
{
   thisWidth = 250;
   thisHeight = 0;


   (function(j){
      var imgSrc = "photo_"+j+".jpg";
      var letterImg = new Image();
      letterImg.onload = function() {
        context.drawImage(letterImg,thisWidth*j,thisHeight);
      }
      letterImg.src = imgSrc;
   })(i);

}

【讨论】:

  • 该死的我正要回答它。 :(
  • 我收到关于 (i) 的语法错误。不好意思,以前没见过这种功能:SyntaxError: missing ; before statement
  • 语法现在正确。我也得到了所有的图像,但它总是最后一个......知道为什么吗?
  • 现在试试,我在闭包中包含了图像创建。
  • letterImg 正在更改,因为它在定义之前没有 var 并且是在全局范围内创建的。
【解决方案2】:

这是解决问题的另一种方法...

letterImg 只是对图像的引用。因此,for 循环被执行了 n 次,每次,letterImg 都会变成一个新的图像。因此,您只能获得最新绘制的图像。

这是代码(当然,将maxImg 数字更改为正确的值。):

images = []; //An array where images are stored.
thisWidth = 250; //This doesn't need to be inside the for-loop.
thisHeight = 0;
maxImg = 342;

//Attach an onload event to an image, that will draw it at (x, y) coordinates.
attach = function(img, x, y)
{
    img.onload = function()
    {
        context.drawImage(img, x, y);
    }
}

for (var i = 0; i <= maxImg; i++)
{
    imgSrc = "photo_" + i + ".jpg";

    images[i] = new Image();
    images[i].src = imgSrc;

    attach(images[i], thisWidth*i, thisHeight);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-11
    • 2022-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 2011-07-21
    相关资源
    最近更新 更多