Canvas How to - Draw circle in animation








Question

We would like to know how to draw circle in animation.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--   w ww  .  java 2 s  . c  om-->
    var c = document.getElementById('c').getContext('2d');
    var duration = 700;
    var delay = 10; 
    var stepT = duration/delay; // steps needed
    var cT = 0; // step counter
    c.fillStyle = 'white'
    var end = 58; // endpoint in percent
    var int = setInterval(function(){
        c.fillRect(0,0,100,100);
        c.strokeStyle = 'orange';
        c.beginPath();
        c.arc(50, 50, 40, -.5*Math.PI, (-.5*Math.PI + 2*Math.PI / 100 * end * cT / stepT));
        c.lineWidth = 10;
        c.stroke();
        if(++cT>stepT){
            clearInterval(int);   
        }
    },delay);
}//]]>  
</script>
</head>
<body>
  <canvas id="c" width="100" height="100"></canvas>
</body>
</html>

The code above is rendered as follows: