HTML and CSS Reference
In-Depth Information
ax = dx * spring;
vx += ax;
ball.x += vx;
ball.draw(context);
}());
};
</script>
</body>
</html>
Test this in your browser, and you'll see something spring-like going on. The problem is that it kind of goes
on forever. Earlier, when the spring was described, we said that it slows down and comes to a stop. But in
this example, the ball builds up the same velocity on each leg of its swing, so it keeps bouncing back and
forth at the same speed. You need something to reduce its velocity and slow it down—which means you
need to apply some friction. Easy enough, just create a friction variable, with a value like 0.95 for
starters. This goes up at the top of the script with the rest of the variables:
var friction = 0.95;
Then multiply vx by friction somewhere in the drawFrame function. Here's the corrected section of the
script ( 06-spring-2.html ):
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
var dx = targetX - ball.x,
ax = dx * spring;
vx += ax;
vx *= friction;
ball.x += vx;
ball.draw(context);
}());
At this point, you have a full-fledged, albeit one-dimensional, spring. Play with this one a lot, and see what
different values for spring and friction do and how they interact. Check out how a different starting
position or target position affects the action of the system, the speed of the ball, and the rate at which it
slows down and comes to a stop.
Just like with easing, the animation loop will continue to apply the minute motion values long after the code
has any visual effects. Again, you can save some calculations by checking if the number is larger than a
minimum distance before applying the friction, like so:
if (Math.abs(vx) > 0.001) {
vx += ax;
vx *= friction;
ball.x += vx;
}
Understanding this spring example will take you a long way. Now you're ready to move on to a two-dimensional spring.
 
Search WWH ::




Custom Search