Canvas How to - Bounce along the rectangle edges








Question

We would like to know how to bounce along the rectangle edges.

Answer


<!--from   ww  w .j ava  2 s .  co m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.7.1.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
var canvas = document.getElementById('mainCanvas');
var ctx;
var x = 300, y = 150;
var dx = 1,  dy = 1;
function init() {
    ctx = canvas.getContext('2d');
    return setInterval(draw, 10);
}
function draw() {
    ctx.clearRect(0,0,300,300);
    ctx.beginPath();
    ctx.arc(x, y, 20, 0, Math.PI*2, true); 
    ctx.closePath();
    ctx.fill();
    x += dx;
    y += dy;
    if (x > 300 || x < 0) {
         dx *= -1;   
    }
    if (y > 300 || y < 0) {
         dy *= -1;   
    }
}
init();
});//]]>  
</script>
</head>
<body>
  <canvas id="mainCanvas" style="background-color: white;" height="300"
    width="300"></canvas>
</body>
</html>

The code above is rendered as follows: