PandaKMusic PandaKMusic - 1 month ago 9
Javascript Question

For-loop not working for JavaScript animation

I am trying to write a for-loop to repeat the animation of the 'explode' path when a shape button is clicked but the for loop isn't working/executing and I can't see where its gone wrong. Aim of the for loop: loop the process of animating the path and then reversing the animation back to its original path. I know that the problem is somewhere in the for loop as the explode.animate() method just before the loop works.

Note: I am using Raphael.js for this animation

var explode = paper.path("M 300,400 l 30,50 l 40,-30 l -10,50 l 40,30 l -50,10 l 10,40 l -60,-40 l -50, 30 l 10,-50 l -60,-10 l 70, -20 z");
explode.attr({'fill':"yellow", 'stroke-width':"4"});
explode.hide();


function explode1() {
explode.animate({path:("M 300,400 l 30,50 l 40,-30 l -10,50 l 40,30 l -50,10 l 10,40 l -60,-40 l -50, 30 l 10,-50 l -60,-10 l 70, -20 z"), 'fill':"yellow"}, 100, 'ease-out');
}

function explode2() {
explode.animate({path:"M 300,380 l 5,70 l 60,-30 l -5,70 l 70,30 l -100,-10 l -50,50 l -30,-50 l -90, 10 l 80,-50 l -60,-20 l 90, 10 z", 'fill':"orange"},100,'ease-in');
}


bomb1.click(function() {
audio.pause();
audio.currentTime = 0;
bomb1.remove();
explode.show();
explode.animate({path:"M 300,380 l 5,70 l 60,-30 l -5,70 l 70,30 l -100,-10 l -50,50 l -30,-50 l -90, 10 l 80,-50 l -60,-20 l 90, 10 z", 'fill':"orange"},100,'ease-in');

for(var i = 0; i < 4; i+=1) {
if (i % 2 == 0) {
explode1();
} else {
explode2();
}
}
});


I have also tried putting the animate methods directly into the for loop instead of writing them as functions and for loop still doesn't work.

bomb1.click(function() {
audio.pause();
audio.currentTime = 0;
bomb1.remove();
explode.show();
explode.animate({path:"M 300,380 l 5,70 l 60,-30 l -5,70 l 70,30 l -100,-10 l -50,50 l -30,-50 l -90, 10 l 80,-50 l -60,-20 l 90, 10 z", 'fill':"orange"},100,'ease-in');

for(var i = 0; i < 5; i+=1) {
if (i % 2 == 0) {
explode.animate({path:("M 300,400 l 30,50 l 40,-30 l -10,50 l 40,30 l -50,10 l 10,40 l -60,-40 l -50, 30 l 10,-50 l -60,-10 l 70, -20 z"), 'fill':"yellow"}, 100, 'ease-out');
} else {
explode.animate({path:"M 300,380 l 5,70 l 60,-30 l -5,70 l 70,30 l -100,-10 l -50,50 l -30,-50 l -90, 10 l 80,-50 l -60,-20 l 90, 10 z", 'fill':"orange"},100,'ease-in');
}
};

Answer

The animation is not synchronous. By that I mean the the for loop will not wait for the animation to finish before performing the next step of the loop. They will all get started at the same time.

What you need to do is trigger the next animation once the first one is complete. RaphaelJS lets you pass a function to the animate() method that gets called when the animation is finished.

See the following question for an example:

animating paths with raphael