Canvas How to - Draw line along points in animation








Question

We would like to know how to draw line along points in animation.

Answer


<!--  w  w  w.  j a v a 2 s .  c  om-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){
    var canvas = document.getElementById("canvasWindow");
    var c = canvas.getContext("2d");
    var curPoint = {
        x : 10,
        y : 10,
        index : 0   
    }
    var points = [{x:10, y:20}, {x:100, y:100}, {x:50, y:150}, {x:10,y:10}, 
                  {x:110,y:210},{x:110,y:110}];
    function toPoints(points){
        var targetPoint = points[curPoint.index];
        var tx = targetPoint.x - curPoint.x,
            ty = targetPoint.y - curPoint.y
        var dist = Math.sqrt(tx*tx+ty*ty),
            rad = Math.atan2(ty,tx);
        var velX = (tx/dist)*1;
        var velY = (ty/dist)*1;
        curPoint.x += velX;
        curPoint.y += velY;
        if(dist < 2){
           curPoint.index++;
        }
        c.fillRect(curPoint.x, curPoint.y, 1, 1);
        if(curPoint.index < points.length){
           setTimeout(function(){toPoints(points)}, 10);
        }
    }
    toPoints(points);
}
</script>
</head>
<body>
  <canvas id="canvasWindow" width="200" height="200"></canvas>
</body>
</html>

The code above is rendered as follows: