【问题标题】:Is it possible to use multiple images in an HTML5 canvas?是否可以在 HTML5 画布中使用多个图像?
【发布时间】:2011-08-05 13:06:19
【问题描述】:

我正在尝试将 10 个不同的图像加载到画布中。我的计划是最终为这些图像制作动画,但现在它们似乎正在相互覆盖。这是我的代码:

var DrawLetters = function()
{
    for (i = 0; i < howManyLetters; i++)
    {
        thisWidth = letters[i][0];
        thisHeight = letters[i][1];
        imgSrc = letters[i][2];
        letterImg = new Image();
        letterImg.onload = function()
        {
            context.drawImage(letterImg,thisWidth,thisHeight);
        }
        letterImg.src = imgSrc;
    }
};

letters 是一个包含 10 个元素的数组,其中每个元素都包含图像的路径。对此的任何帮助将不胜感激。

【问题讨论】:

  • 您是否意识到您在 for 循环中使用了全局变量?
  • 我愿意。目前这只是一个概念证明,并不意味着通过 JSLint 分析。我只是想让这些部分发挥作用,以证明我可以在完全写出之前做我想做的事情。

标签: javascript image html canvas


【解决方案1】:

我已经尝试过您的代码,并且 onload 方法始终使用变量的 LAST 值,而不是迭代数组时的值。

尝试将 X 和 Y 设置为图像对象的属性:

// I assume you are storing the coordinates where the letters must be
letterImg.setAtX = letter[i][XPOS];
letterImg.setAtY = letter[i][YPOS];

在加载时:

context.drawImage(this, this.setAtX, this.setAtY);

this 是引发onload 事件的图像。

编辑我已经更改了用于携带坐标的属性。现在它们是 setAtX/Y。您不能使用 x 和 y,因为它们是保留的。

【讨论】:

  • 工作就像一个魅力!谢谢!
【解决方案2】:

您将它们绘制在同一点上。 drawImage 不关心给定参数的高度或宽度;它只需要一个图像和一个坐标。见https://developer.mozilla.org/en/Canvas_tutorial/Using_images

因此,您需要为图像提供更多数据;类似:

    thisWidth = letters[i][0];
    thisHeight = letters[i][1];
    imgSrc = letters[i][2];
    thisX = letters[i][3]; //<---
    thisY = letters[i][4]; //<---
    letterImg = new Image();
    letterImg.onload = function()
    {
        context.drawImage(letterImg, thisX, thisY, thisWidth, thisHeight);
        //or, just
        context.drawImage(letterImg, thisX, thisY);
    }
    letterImg.src = imgSrc;

编辑:刚刚有一个想法 - 你可以动态地做到这一点:

context.drawImage(letterImg, letters[i-1][0]+thisWidth, letters[i-1]+thisHeight, thisWidth, thisHeight);

通过这种方式,您必须检查内容,但我认为您可以了解总体意图。

【讨论】:

  • 很抱歉我的变量名不清楚。它们不应该是 thisWidth 和 thisHeight,它们实际上是 X、Y 坐标,它们都是唯一的。
【解决方案3】:

您必须每次重新定位绘图开始位置,以免图像被覆盖。

[context . drawImage(image, dx, dy, dw, dh)][1]

链接上有一张图片解释了每个参数的含义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-12
    • 2017-12-12
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    相关资源
    最近更新 更多