HTML5 CANVAS 上的多个对象,仅绘制第一个项目
请考虑这样的代码,在每个动画循环中调用 draw()
函数,其中清除舞台并将渐变应用于背景,并更改形状的 x,y:
draw = function() {
for ( i = 0; i < shapes.length; i++ )
{
draw_sample_shape(i);
draw_coords(i);
}
}
draw_sample_shape = function(shape) {
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(shapes[shape].x, shapes[shape].y, 240, 0, Math.PI*2, false);
ctx.closePath();
ctx.fill();
}
draw_coords(shape) {
coords = shapes[shape].coords;
ctx.globalCompositeOperation = "destination-out";
ctx.beginPath();
ctx.moveTo(coords[0].x, coords[0].y);
for ( i = 1; i < coords.length; i++ )
{
if (coords[i].y == 'X' && coords[i].x == 'X')
{
ctx.closePath();
ctx.fill();
ctx.moveTo(0, 0);
ctx.beginPath();
if (typeof(coords[i+1]) != 'undefined')
{
ctx.moveTo( (coords[i+1].x), (coords[i+1].y) );
}
}
else
{
ctx.lineTo((coords[i].x), (coords[i].y));
}
}
ctx.closePath();
ctx.fill();
}
现在一切都很完美,除非我在我的 draw()
函数中调用 draw_coords()
- 问题是它只绘制第一个形状并为其设置动画,并跳过其余的形状。当我跳过这个调用时,它工作正常。
我使用 [X,X] 坐标重置绘图,并开始下一个形状。 有人能告诉我这有什么问题吗?为什么当我绘制坐标时它只将它们绘制在第一个元素上?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想我知道你为什么会遇到问题。就是这一行:
for ( i = 0; i
你说的是
i = 0
而不是var i = 0
代码>.这意味着
i
是全局的。这意味着
draw_coords
中的i
实际上破坏了draw()
中的i
!因此,您从
draw()
中的第一个对象开始,其中i
为0
,然后进入draw_coords,它采用相同的i
变量并将其递增到较大的值,例如10
。然后,当第一个draw_coords完成后,它会返回绘制并查看i
(现在是10
)是否小于shapes.length(可能类似于6) 。也不少,所以draw
中的 for 循环认为自己已经完成了!您肯定不希望这样,因此将两个 for 循环更改为 var:
for (var i = 0;
您在这里遇到的问题将会消失。
I think I know why you're getting a problem. It's this line:
for ( i = 0; i < shapes.length; i++ )
You are saying
i = 0
instead ofvar i = 0
.This means that
i
is global.This means that the
i
indraw_coords
is actually clobbering youri
indraw()
!So you start on the first object in
draw()
withi
being0
, then you go into draw_coords and it takes the samei
variable and increments it to something large, like10
. Then when the first draw_coords is done it goes back to draw and sees ifi
, which is now10
, is less than shapes.length (which might be something like 6). It's not less, so the for loop indraw
considers itself done!You definitely don't want this, so change both of your for loops to have var:
for (var i = 0;
And the problem you're having here about will go away.