Canvas How to - Bounce four balls along walls








Question

We would like to know how to bounce four balls along walls.

Answer


<!--<!--   w  w  w. j  av  a 2 s . c om-->
Code revised from
http://fiddle.jshell.net/7nJDV/
-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
var context;
var width = 500, height = 500;
var balls = [
    { x:   0, y:   0, dx: 3, dy: 7, r: 10 },
    { x: 150, y: 250, dx: 7, dy: 3, r: 10 },
    { x: 200, y: 200, dx: 6, dy: 4, r: 10 },
    { x: 250, y: 250, dx: 4, dy: 6, r: 10 }
];
function init()
{
    var myCanvas = document.getElementById('c');
    context = myCanvas.getContext('2d');
    setInterval(onTick, 10);
}
function onTick()
{
    context.clearRect(0, 0, width, height);
    context.fillStyle = "#0000ff";
    context.beginPath();
    var i;
    for (i = 0; i < balls.length; i++)
    {
        moveBall(balls[i]);
        drawBallPath(balls[i], context);
    }
    context.fill();
}
function drawBallPath(ball, context)
{
    context.moveTo(ball.x + ball.r, ball.y);
    context.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2, true);
}
function moveBall(ball)
{
    if (ball.x < 0 || ball.x > width) ball.dx = -ball.dx;
    if (ball.y < 0 || ball.y > height) ball.dy = -ball.dy;
    ball.x += ball.dx;
    ball.y += ball.dy;
}
init();
}//]]>  
</script>
</head>
<body>
  <canvas id='c' width="500px" height="500px"></canvas>
</body>
</html>

The code above is rendered as follows: