Canvas Bouncing Balls
HTML
<canvas id="thecanvas" width=1200 height=800></canvas>
CSS
#thecanvas { border: 1px solid; }
JavaScript
var cw = window.innerWidth, ch = window.innerHeight;
var canvas, context;
function Ball(x, y, dx, dy, radius, color) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.elasticity = radius/2;
this.radius = radius;
this.w = radius;
this.h = radius;
this.color = color;
};
// This array will hold all balls in the canvas
var balls = [];
var AddBall = function() {
var radius = (Math.random()*55)+5; // 5 < radius < 60
var x = Math.random()*cw;
var y = Math.random()*ch;
if (x-radius < 0) {x += radius;}
if (x+radius > cw) {x -= radius;}
if (y-radius < 0) {y += radius;}
if (y+radius > ch) { y -= radius;}
var dx = (Math.random()*4 + 1);
var dy = (Math.random()*4 + 1);
var color = "#"+((1<<24)*Math.random()|0).toString(16);
var b = new Ball(x, y, dx, dy, radius, color);
balls.push(b);
};
var AddNBalls = function(n) {
for (var i = 0; i < n; i++){
AddBall();
}
};
function drawFrame() {
context.clearRect(0,0, cw, ch);
context.beginPath();
for (var i=0; i<balls.length; i++) {
var ball = balls[i];
ball.x += ball.dx;
ball.y += ball.dy;
var collisionRight = ball.x + ball.w - cw;
var collisionLeft = ball.x - ball.w;
// Bounce if ball hits side
if (collisionLeft<0) {
ball.dx -= -collisionLeft;
ball.w-= -collisionLeft;
ball.h+= -collisionLeft;
}
if (collisionRight>0) {
ball.dx -= collisionRight;
ball.w -= collisionRight;
ball.h += collisionRight;
}
var collisionBottom = ball.y + ball.h - ch;
var collisionTop = ball.y - ball.h;
// Bounce if ball hits bottom or top
if (collisionTop<0) {
ball.dy -= -collisionTop;
ball.w += -collisionTop;
ball.h -= -collisionTop;
}
if (collisionBottom>0)...