是否可以在 HTML5 画布中使用多个图像?
我正在尝试将 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 个元素的数组,其中每个元素都包含图像的路径。对此的任何帮助将不胜感激。
I'm trying to load 10 different images into a canvas. My plan is to eventually animate these images but right now they seem to be overwriting one another. Here is my code:
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 is an array with 10 elements where each element contains a path to the image. Any help on this would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我已经尝试过您的代码,并且 onload 方法始终使用变量的最后一个值,而不是迭代数组时的值。
尝试将 X 和 Y 设置为图像对象的属性:
在 onload 上:
this
是引发onload
事件的图像。编辑 我更改了用于携带坐标的属性。现在它们已设置AtX/Y。您不能使用 x 和 y,因为它们是保留的。
I've tried your code and the onload method always use the LAST value of the vars, not the value when the array was iterated.
Try setting the X and the Y to properties of the image object:
and on the onload:
this
is the image raising theonload
event.Edit I've changed the properties used to carry the coordinates. Now they're setAtX/Y. You cannot use x and y because they're reserved.
你把它们画在同一个点上。 drawImage 不关心给定参数的高度或宽度;它只需要一个图像和一个坐标。请参阅 https://developer.mozilla.org/en/Canvas_tutorial/Using_images
所以,您需要为您的图像提供更多数据;像这样的东西:
编辑:只是有一个想法 - 你可以以神奇的方式做到这一点:
通过这种方式,你必须检查东西,但我认为你得到了总体意图。
You're drawing them on the same point. drawImage doesn't care about the height or width with your given parameters; it just wants an image and a coordinate. See https://developer.mozilla.org/en/Canvas_tutorial/Using_images
So, you're gonna need to give your images more data; something like:
Edit: Just had a thought - you can do it dymagically:
With this way you'll have to check for stuff, but I think you get the overall intention.
您必须每次都重新定位绘制开始位置,以免图像被覆盖。
链接上有一张图片解释了每个参数的含义。
You have to reposition the draw start position every time so the images arent overwritten.
There's an image on the link explaning what every parameter means.