HTML

<!doctype html>
<head>
<meta language="utf-8">
<title>JavaScript Ball Game</title>
<script src="bouncing.js"></script>
</head>
<body>
<canvas id="game" width="300" height="300"></canvas>
</body>
</html>

JavaScript

var canvas;
var g;
var r;
var c1, c2;
var grad;
var x, y, vx, vy, sep;
var scale;
window.onload=ballGame;

function ballGame(){
canvas=document.getElementById("game");
g=canvas.getContext("2d");
canvas.style.backgroundColor="#456";
scale=16;
r=canvas.width/scale;
c1="#eee";
c2="#b90";
n=10;
setup();
setInterval(moveBall, 40);
}

function setup(){
x = new Array(n);
y = new Array(n);
vx = new Array(n);
vy = new Array(n);
for (var i=0;i<n;i++){
var theta=6.2832/n*i;
x[i]=canvas.width/2+(canvas.width/4*Math.cos(theta));
y[i]=canvas.height/2+(canvas.height/4*Math.sin(theta));
vx[i]=Math.random()*8-4;
vy[i]=Math.random()*8-4;
drawBall(x[i],y[i],c1,c2);
}
}

function moveBall(){
g.clearRect(0,0, canvas.width, canvas.height);
for(var i=0;i<n;i++){
collisionTest(i);
if(x[i]>=canvas.width-r) vx[i]=-Math.abs(vx[i]);
else if(x[i]<=r) vx[i]=Math.abs(vx[i]);
if(y[i]>=canvas.height-r) vy[i]=-Math.abs(vy[i]);
else if(y[i]<=r) vy[i]=Math.abs(vy[i]);
x[i]+=vx[i];
y[i]+=vy[i];
drawBall(x[i],y[i],c1,c2);
}
}
function drawBall(a,b,c,d){
grad=g.createRadialGradient(a-r/2, b-r/2, 0, a-r/2, b-r/2, 2*r);
grad.addColorStop(0, c);
grad.addColorStop(1, d);
g.beginPath();
g.fillStyle=grad;
g.arc(a, b, r, 0, 6.2832);
g.fill();
}

function collisionTest(i){
for(var j=0;j<n;j++){
sep=Math.sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]))
if((sep<=2*r)&&(i!=j)) bounce(i,j);
}
}

function bounce(i,j){
var tempvx=vx[i];
var tempvy=vy[i];
vx[i]=vx[j];
vy[i]=vy[j];
vx[j]=tempvx;
vy[j]=tempvy;
x[i]+=vx[i];
y[i]+=vy[i];
x[j]+=vx[j];
y[j]+=vy[j];
}

These examples are presented without explanation. For a more complete treatment of the JavaScript code you can refer to "Start Programming with JavaScript" by Bill Tait, which is available in Kindle and paperback format from Amazon.