HMdeveloper
HMdeveloper

Reputation: 2884

Animating the drawn line

I am using the following code to draw a line and it works well:

var centerX =  $("#myCanvas").width()/ 2;
var centerY = $("#myCanvas").height()/ 2;
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
 ctx.fillStyle = 'white';
ctx.fill();
ctx.beginPath();
ctx.moveTo(0,centerY );
ctx.lineTo( centerX*2,centerY);
ctx.stroke();

Now I want to animate the line while it is drawn but I do not know how to do it.I tried to do it with animate but I could not .Can anyone help?

Here is the fiddle link as well:

fiddle

Upvotes: 0

Views: 73

Answers (1)

markE
markE

Reputation: 105015

You can use linear interpolation (lerping) to calculate the points on a line from start to end.

    var cx=canvas.width/2;
    var cy=canvas.height/2;
    var pct=0.50;

    // calc the value that is x% between a & b

    var lerp=function(a,b,x){ return(a+x*(b-a)); };

    // use lerping to calc the value of x at the midpoint (50%) of the line

    var x=lerp(0,cx*2,pct);

Then you can incrementally draw a line from start to end with the requestAnimationFrame loop.

function animate(){
    if(pct<100){requestAnimationFrame(animate);}
    var x=lerp(0,cx*2,pct/100);
    drawLine(0,cy,x,cy);
    pct++;    
}

Here's example code and a Demo: http://jsfiddle.net/m1erickson/6P6jx/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cx=canvas.width/2;
    var cy=canvas.height/2;
    var lerp=function(a,b,x){ return(a+x*(b-a)); };
    var pct=0;

    animate();

    function animate(){
        if(pct<100){requestAnimationFrame(animate);}
        var x=lerp(0,cx*2,pct/100);
        drawLine(0,cy,x,cy);
        pct++;    
    }

    function drawLine(x0,y0,x1,y1){
        ctx.beginPath();
        ctx.moveTo(x0,y0);
        ctx.lineTo(x1,y1);
        ctx.stroke();
    }

}); // end $(function(){});
</script>
</head>
<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

Upvotes: 1

Related Questions