Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to animate drawing lines on canvas

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();

http://jsfiddle.net/s4gWK/1/

like image 569
Mufeed Ahmad Avatar asked May 29 '14 17:05

Mufeed Ahmad


2 Answers

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:

// define the path to plot
var vertices=[];
vertices.push({x:0,y:0});
vertices.push({x:300,y:100});
vertices.push({x:80,y:200});
vertices.push({x:10,y:100});
vertices.push({x:0,y:0});

// calc waypoints traveling along vertices
function calcWaypoints(vertices){
    var waypoints=[];
    for(var i=1;i<vertices.length;i++){
        var pt0=vertices[i-1];
        var pt1=vertices[i];
        var dx=pt1.x-pt0.x;
        var dy=pt1.y-pt0.y;
        for(var j=0;j<100;j++){
            var x=pt0.x+dx*j/100;
            var y=pt0.y+dy*j/100;
            waypoints.push({x:x,y:y});
        }
    }
    return(waypoints);
}

Then you can use requestAnimationFrame to animate each incremental line segment:

// calculate incremental points along the path
var points=calcWaypoints(vertices);


// variable to hold how many frames have elapsed in the animation
// t represents each waypoint along the path and is incremented in the animation loop
var t=1;


// start the animation
animate();

// incrementally draw additional line segments along the path
function animate(){
    if(t<points.length-1){ requestAnimationFrame(animate); }
    // draw a line segment from the last waypoint
    // to the current waypoint
    ctx.beginPath();
    ctx.moveTo(points[t-1].x,points[t-1].y);
    ctx.lineTo(points[t].x,points[t].y);
    ctx.stroke();
    // increment "t" to get the next waypoint
    t++;
}
like image 180
markE Avatar answered Sep 21 '22 19:09

markE


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).

(function() {
    var lastTime = 0;
    var vendors = ['webkit', 'moz'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame =
          window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); },
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());

So the big question is, how does this work? You pretty much just need to do this:

function gameLoop () {

  window.requestAnimationFrame(gameLoop);

  renderLine();

}
var counter = 0; 
var old_position = {x: 0, y: 0};
var new_position = {x: 0, y: 0}; 
var width = 10;
var height = 10;
function renderLine(){

 /* Here you clear the old line before you draw the new one */
 context.clearRect(old_position.x, old_position.y, width, height) 

 /* you update your new position */
 new_position = {x: 100, y: 200};  
/* Here you call your normal moveTo and lineTo and stroke functions */

 /* update old position with the nwe position */
 old_position = new_position;

}

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/

like image 31
kemicofa ghost Avatar answered Sep 22 '22 19:09

kemicofa ghost