san A san A - 4 months ago 19
Javascript Question

How do I animate this path?

I am new to Canvas in HTML5.
I made one path on the canvas, but I want the path to animate and not flash at once. How can I do so ?

below is the JS code ::

$('#draw').click(function() {
var a,b;
a=b=5;

context.clearRect(0, 0, 500, 500);

context.moveTo(centerx, centery);
context.beginPath();
context.strokeStyle = "#000";
for (i = 0; i < 120; i++) {
angle = 0.1 * i;
x = centerx + (a + b * angle) * Math.cos(angle);
y = centery + (a + b * angle) * Math.sin(angle);
context.lineTo(x, y);
context.stroke();
}

});


What I have tried so far:

used
setInterval()
,
setTimeout()
both to no avail. Tried Making different functions for the path rendering and calculation of x and y values but that also did not work ! Also by the documentation, the path is not drawn until
context.stroke()
is called which makes me wonder if it is even possible to animate ?

EDIT:: JSFiddle Link
https://jsfiddle.net/sankh_15A/7L3a4rkL/

Answer

To build an animation you need to recursively draw a piece of your spiral and eventually break out at a certain point.

The most optimized method to draw such animation is window.requestAnimationFrame , but you could do it also with setIterval or setTimeout.

An example would be :

var i = 0;
function render(){
   i++;
   angle = 0.1 * i;
   x = centerx + (a + b * angle) * Math.cos(angle);
   y = centery + (a + b * angle) * Math.sin(angle);
   context.lineTo(x, y);  
   context.stroke();
   if (i <720)
    requestAnimationFrame(render);
  }
requestAnimationFrame(render);//start animation

fiddle