HTML and CSS Reference
In-Depth Information
Finally, when all of the balls are in place, you begin a new path, move the drawing cursor to the mouse
position, and then draw a line to each successive ball, creating the rubber band holding them all together.
The friction in this example was pushed to 0.9 to force things to settle down a bit quicker.
You could make this example a bit more flexible, by creating an array to hold references to each object in
the chain, and iterating through that array to move each one, and then draw the lines. This would just take
a few changes. First, you'd need a couple of new variables for the array and the number of objects to
create:
var balls = [],
numBalls = 5;
At the top of the script in a while loop, we initialize each ball and add it to the array:
while (numBalls--) {
balls.push(new Ball(20));
}
Finally, in drawFrame we pass each ball to the new draw function. This function takes two arguments, an
instance of our Ball class, and it's index position in an array (which is provided by Array.forEach ). We
move the first ball to the mouse position, and each remaining ball to the ball prior to it, drawing a line
between them. It loops through all the balls in the array, moving and drawing a line to each one in turn.
You can add as many objects as you want simply by changing the value of the one variable, numBalls .
function draw (ballB, i) {
//if first ball, move to mouse
if (i === 0) {
move(ballB, mouse.x, mouse.y);
context.moveTo(mouse.x, mouse.y);
} else {
var ballA = balls[i-1];
move(ballB, ballA.x, ballA.y);
context.moveTo(ballA.x, ballA.y);
}
context.lineTo(ballB.x, ballB.y);
context.stroke();
ballB.draw(context);
}
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
balls.forEach(draw);
}());
You can see the result in Figure 8-3 and can find this in document 11-chain-array.html .
Search WWH ::




Custom Search