Canvas How to - Draw image in animation








Question

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

Answer


<!--from   w w w.  j a  v  a  2 s  . com-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
var ratio = 0;
var image = new Image();
image.src = "http://www.java2s.com/style/download.png";
image.onload = function() {
    var canvas = document.querySelector("canvas");
    var ctx = canvas.getContext("2d");
    setInterval(function() {
        ratio += 0.01;
        ratio = ratio % 1;
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        //Draw "empty" image
        ctx.globalAlpha = 0.6;
        ctx.drawImage(image, 0, 0);
        //Draw actual pizza image
        ctx.globalAlpha = 1;
        ctx.drawImage(image, 0, 0);
        //Draw mask
        ctx.globalCompositeOperation = "destination-atop";
        ctx.beginPath();
        ctx.moveTo(image.width / 2, image.height / 2);
        ctx.arc(image.width / 2, image.height / 2, image.width / 2, -Math.PI / 2, (-Math.PI / 2) + ((Math.PI * 2) * ratio), false);
        ctx.fill();
    }, 100);
};
});//]]>  
</script>
</head>
<body>
  <canvas width="512" height="512"></canvas>
</body>
</html>

The code above is rendered as follows: