Reputation: 78
Please consider such code, draw()
function is called in each animation loop, where stage is cleared and gradient is applied to a background and x,y are changed for shapes:
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();
}
Now everything works perfect, unless I call draw_coords()
in my draw()
function - the problem is it draws and animates only the first shape, and skips the rest of them. When I skip this call it works OK.
I use the [X,X] coords to reset drawing, and start the next shape. Can someone tell me what is wrong with that? and why when I draw that coords it only draws them on first element?
Upvotes: 1
Views: 962
Reputation: 63822
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 of var i = 0
.
This means that i
is global.
This means that the i
in draw_coords
is actually clobbering your i
in draw()
!
So you start on the first object in draw()
with i
being 0
, then you go into draw_coords and it takes the same i
variable and increments it to something large, like 10
. Then when the first draw_coords is done it goes back to draw and sees if i
, which is now 10
, is less than shapes.length (which might be something like 6). It's not less, so the for loop in draw
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.
Upvotes: 1