Canvas How to - Rotate square in animation








Question

We would like to know how to rotate square in animation.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!-- w  w  w. ja va2s.c om-->
    init();
    function init(){
        beware();
        setInterval(beware,120);
    }
    function beware(){
        var my_canvas = document.getElementById('canvas');
        var context = my_canvas.getContext("2d");
        context.clearRect(0,0,200,200);
        context.beginPath();
        context.arc(100,100,100,0,2*Math.PI);
        context.stroke();
        context.save();
        context.translate(100,100);
        var time = new Date();
        context.rotate( ((2*Math.PI)/60) * time.getSeconds() + ((2*Math.PI)/60000) * time.getMilliseconds() );
        context.fillStyle = "#DC143C";
        context.fillRect(-50,-50,100,100);
        context.fillStyle = "#8B008B";
        context.font = "20px Garamond";
        context.fillText("Hi",-40,-55);
        context.restore();
    }
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width="200" height="200"></canvas>
</body>
</html>

The code above is rendered as follows: