2 of 4
added 3 characters in body; edited tags; edited title
200_success
• 141.1k
• 21
• 183
• 466

# Make this bouncing ball Javascript more efficient?

I have been using this code for a while for a project at work. Actually I got it from a friends who got it from a book I am certain off. But either way it worked for my demonstration. But the other night I decided to sit down and see if I could make it into all functions and then to see about moving the variables up to the top of each function. Which would be normal for simple programming and every thing should work but when I did this the code crashed and burned (Didn't show anything in the canvas) It should show bouncing balls.

<!doctype html>
<html>
<title>Bounding Balls</title>
<script src="modernizr.js"></script>
<script type="text/javascript">

canvasApp();
}

function canvasSupport () {
return Modernizr.canvas;
}

function canvasApp() {
if (!canvasSupport()) {
return;
}

function  drawScreen () {
context.fillStyle = '#EEEEEE';
context.fillRect(0, 0, theCanvas.width, theCanvas.height);
//Box
context.strokeStyle = '#000000';
context.strokeRect(1,  1, theCanvas.width-2, theCanvas.height-2);
//Place balls

context.fillStyle = "#00AA00";
var ball;//object

for (var i =0; i <balls.length; i++) {
ball    = balls[i];
ball.x += ball.xunits;
ball.y += ball.yunits;

context.beginPath();
context.closePath();

context.fill();

if (ball.x > theCanvas.width || ball.x < 0 ) {
ball.angle = 180 - ball.angle;
updateBall(ball);
} else if (ball.y > theCanvas.height || ball.y < 0) {
ball.angle = 360 - ball.angle;
updateBall(ball);
}
}

}

function updateBall(ball) {
ball.radians = ball.angle * Math.PI/ 180;
}

var numBalls = 100 ;
var maxSize = 8;
var minSize = 5;
var maxSpeed = maxSize+5;
var balls = new Array();
var tempBall;
var tempX;
var tempY;
var tempSpeed;
var tempAngle;
var tempXunits;
var tempYunits;

theCanvas = document.getElementById('canvasOne'); // <-- Code will not work if this is moved to the top of the method ---
context = theCanvas.getContext('2d');

for (var i = 0; i < numBalls; i++) {
tempAngle =  Math.floor(Math.random()*360);
tempRadians = tempAngle * Math.PI/ 180;

balls.push(tempBall);
}

function gameLoop() {
window.setTimeout(gameLoop, 20);
drawScreen()
}

gameLoop();
}
</script>