HTML and CSS Reference
In-Depth Information
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script src="ball.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
balls = [],
numBalls = 80,
gravity = 0.5;
for (var ball, i = 0; i < numBalls; i++) {
ball = new Ball(2, Math.random() * 0xffffff);
ball.x = canvas.width / 2;
ball.y = canvas.height;
ball.vx = Math.random() * 2 - 1;
ball.vy = Math.random() * -10 - 10;
balls.push(ball);
}
function draw (ball) {
ball.vy += gravity;
ball.x += ball.vx;
ball.y += ball.vy;
if (ball.x - ball.radius > canvas.width ||
ball.x + ball.radius < 0 ||
ball.y - ball.radius > canvas.height ||
ball.y + ball.radius < 0) {
ball.x = canvas.width / 2;
ball.y = canvas.height;
ball.vx = Math.random() * 2 - 1;
ball.vy = Math.random() * -10 - 10;
}
ball.draw(context);
}
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
balls.forEach(draw);
}());
};
</script>
</body>
</html>
You begin at the top of the script by setting all the particles at the starting point and giving them each an
initial random upward velocity.
The
drawFrame
function loops through all the elements of the
balls
array, passing each ball as a
parameter to the
draw
function. This function adds
gravity
to the ball's
vy
value, adds the velocity to the
ball's position, and then checks to see whether the ball has crossed any boundaries. If it has, the ball gets