Canvas How to - Shake Image animation








Question

We would like to know how to shake Image animation.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--from w w  w.jav  a  2  s .  c o m-->
    var c = document.getElementById("canvas");
    var ctx = c.getContext("2d");
    var image = {};
    var hero = {
        name : "Hero",
        image : "http://www.java2s.com/style/download.png",
        posX : 0,
        posY : 0,
        sizeX : 75,
        sizeY : 72,
        frames : 0,
        ready : false
    }
    function loadImage(name) {
        image[name] = new Image();
        image[name].onload = function () {
            hero.ready = true;
        };
        image[name].src = name;
    }
    function draw() {
        if (hero.ready){
            ctx.clearRect (0 , 0, 500 , 500 );
            ctx.shadowColor = "rgba( 0, 0, 0, 0.1 )";
            ctx.shadowOffsetX = 15;
            ctx.shadowOffsetY = -10;
            ctx.drawImage(image[hero.image],hero.frames * hero.sizeX, 0, hero.sizeX, hero.sizeY, hero.posX, hero.posY, hero.sizeX, hero.sizeY);
        }
        hero.frames++;
        if (hero.frames >= 2) hero.frames = 0;
        setTimeout( draw, 1000 / 5 );
    }
    
    loadImage(hero.image);
setTimeout( draw, 1000 / 5 );
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width="500" height="500">:)</canvas>
</body>
</html>

The code above is rendered as follows: