Canvas How to - Bounce along ground








Question

We would like to know how to bounce along ground.

Answer


<!--  w  w w  .ja va  2s.co m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var x = 0, y = 0,  r = 10;
    var dx = 2, dy = 4;
    var WIDTH = 400, HEIGHT = 400; 
    var speed = 15;
    var c = document.getElementById("myCanvas");
    var cxt = c.getContext("2d");
    function clear() {
       ctx.clearRect(0, 0, WIDTH, HEIGHT);
    }
    function init() {
       return setInterval(draw, speed);
    }
    function drawCircle(x,y,r) {
        cxt.clearRect(0, 0, 400, 400);
        cxt.beginPath();
        cxt.arc(x, y, r, 0, Math.PI * 2, false);
        cxt.closePath();
        cxt.fillStyle = "#006699";
        cxt.fill();
    }
    function draw(){
       drawCircle(x, y, r);
       if (x + dx > WIDTH || x + dx < 0)
          dx = -dx;
       if (y + dy > HEIGHT || y + dy < 0)
          dy = -dy;
       x += dx;
       y += dy;
    }
    init();
}//]]>  
</script>
</head>
<body>
  <canvas id="myCanvas" width="400" height="400"></canvas>
</body>
</html>

The code above is rendered as follows: