HTML and CSS Reference
In-Depth Information
context = canvas.getContext('2d'),
log = document.getElementById('log'),
balls = [],
numBalls = 10;
for (var ball, i = 0; i < numBalls; i++) {
ball = new Ball(20);
ball.id = "ball" + i;
ball.x = Math.random() * canvas.width;
ball.y = Math.random() * canvas.height;
ball.vx = Math.random() * 2 - 1;
ball.vy = Math.random() * 2 - 1;
balls.push(ball);
}
function draw (ball, pos) {
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) {
balls.splice(pos, 1); //remove ball from array
if (balls.length > 0) {
log.value = "Removed " + ball.id;
} else {
log.value = "All gone!";
}
}
ball.draw(context);
}
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
var i = balls.length;
while (i--) {
draw(balls[i], i);
}
}());
};
</script>
</body>
</html>
This should be easy to follow. First, create 10 object instances of Ball , randomly placing them on the
canvas, assigning them random x and y velocities, and pushing them into an array.
The drawFrame function is our typical animation loop that clears our canvas, iterates over each ball in the
array, and passes it to the draw function. This function applies the ball's velocity to move it around, checks
the boundaries, and removes any out-of-bounds balls from the array. The parameters to Array.splice
are the index position to start removing elements at, and the amount of elements to remove. In this
Search WWH ::




Custom Search