Canvas How to - Create a Bouncing ball animation








Question

We would like to know how to create a Bouncing ball animation.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!-- w w w. j  a v a2  s  . co m-->
    window.requestAnimationFrame = (function(){
        return  window.requestAnimationFrame       ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame    ||
            function( callback ){
                window.setTimeout(callback, 6000 / 60);
            };
    })();
    var context;
    var canvas;
    var dx= 20, dy= 20;
    var y=150,  x=10;
    var oldX = x;
    var oldY = y;
    var rad = 20;
    var dia = rad*2;
    function draw() {
      context.clearRect(oldX - 2, oldY -2 ,dia +4,dia +4);
        context.drawImage(canvas,x, y);
        oldX = x;
        oldY = y;
      if( x<0 || x>300) dx=-dx;
      if( y<0 || y>300) dy=-dy;
        x+=dx;
      y+=dy;
        requestAnimationFrame(draw);
    }
    function createBall() {
        canvas = document.createElement('canvas');
        canvas.width = dia;
        canvas.height = dia;
        var ctx = canvas.getContext('2d');
      ctx.beginPath();
      ctx.fillStyle="red";
      ctx.arc(rad,rad,rad,0,Math.PI*2,true);
      ctx.closePath();
      ctx.fill();
    }
    createBall();
    context= myCanvas.getContext('2d');
    draw();
}//]]>  
</script>
</head>
<body>
  <canvas id="myCanvas" width="300" height="300"></canvas>
</body>
</html>

The code above is rendered as follows: