I have created some lines connecting with each other on canvas. Now I want to animate these lines while drawing on canvas.
Can anyone please help?
here is my code and fiddle URL:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.moveTo(0,0,0,0);
ctx.lineTo(300,100);
ctx.stroke();
ctx.moveTo(0,0,0,0);
ctx.lineTo(10,100);
ctx.stroke();
ctx.moveTo(10,100,0,0);
ctx.lineTo(80,200);
ctx.stroke();
ctx.moveTo(80,200,0,0);
ctx.lineTo(300,100);
ctx.stroke();
The idea is to draw and draw and draw several different lines in a loop to have the illusion that it's "animating". But that is the concept of animation anyway.
So determine what animation you want to do, and find out a way you can draw each frame in a loop.
That's the concept anyway. But I'd advise you use libraries for this.
Fabric.js (http://fabricjs.com/) and KineticJS (http://kineticjs.com/) are the libraries/frameworks I'd point you to.
I understand that your want the lines to extend incrementally along the points in your path using animation.
A Demo: http://jsfiddle.net/m1erickson/7faRQ/
You can use this function to calculate waypoints along the path:
Then you can use requestAnimationFrame to animate each incremental line segment:
EDIT: I misunderstood your original post. For your situation you do not need to clear the previous animation, only when the animation is complete to start it all over.
jsfiddle : http://jsfiddle.net/Grimbode/TCmrg/
Here are two websites that helped me understand how animations work.
http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/
In this article William speaks sprite animations, which of course isn't what you are interested in. What is interesting is that he uses a recursive loop function created by Paul Irish.
http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
This function will attempt to spin 60 times per second (so essentially at 60 fps).
So the big question is, how does this work? You pretty much just need to do this:
After this step, your question will probably like. "Ok, I have some kind of animation going on, but I don't want my line animation to spin at 60 fps". If you read williams post he uses "ticks".
The websites I linked do a much better job at explaining than I could. I suggest you read up on them. [= I had fun reading them.
AND: Here is your jfiddle :)
http://jsfiddle.net/Grimbode/TCmrg/