[英]Is it possible to use multiple images in an HTML5 canvas?
我正在尝试将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个元素的数组,其中每个元素都包含一个指向图像的路径。 任何有关这方面的帮助将不胜感激。
我已经尝试过你的代码,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];
并在onload上:
context.drawImage(this, this.setAtX, this.setAtY);
this
是提升onload
事件的图像。
编辑我已经更改了用于携带坐标的属性。 现在他们被设置为AtX / Y. 你不能使用x和y,因为它们是保留的。
你在同一点上绘制它们。 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);
通过这种方式你将不得不检查东西,但我认为你得到了整体意图。
您必须每次都重新定位绘制开始位置,以免图像被覆盖。
[context . drawImage(image, dx, dy, dw, dh)][1]
链接上有一个图像,解释了每个参数的含义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.