Canvas How to - Grow line in animation








Question

We would like to know how to grow line in animation.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.7.1.js'></script>
<script type='text/javascript'>
$(window).load(function(){<!--from   ww w. ja  va2 s . c  o m-->
    var canvas = $("#paper")[0];
    var c = canvas.getContext("2d");
    var startX = 50;
    var startY = 50;
    var endX = 100;
    var endY = 100;
    var amount = 0;
    setInterval(function() {
        amount += 0.05; 
        c.clearRect(0, 0, canvas.width, canvas.height);
        c.strokeStyle = "black";
        c.moveTo(startX, startY);
        c.lineTo(startX + (endX - startX) * amount, startY + (endY - startY) * amount);
        c.stroke();
    }, 30);
});
</script>
</head>
<body>
  <canvas id="paper" width="500" height="500"></canvas>
</body>
</html>

The code above is rendered as follows: