HTML and CSS Reference
In-Depth Information
a straight line. That's because its velocity starts out as zero, and the only force acting on it is the pull
toward the target, so it goes in a straight line toward its target.
To make things a little more interesting, initialize vx to something other than 0—try something like 50.
Now, you have motion that looks a little more loose and fluid. But you're only getting started, it gets a lot
cooler.
Springing to a moving target
It probably won't surprise you that springing doesn't require the target to be the same on each frame.
When we covered easing, you saw a quick and easy example of the ball following the mouse. It's pretty
easy to adapt that example to make the ball spring to the mouse. Instead of the targetX and targetY you've
been using, use the mouse coordinates. In springing, as with easing, the distance to the target is always
calculated newly on each frame. Acceleration is based on that, and that acceleration is added to the velocity.
The effect is very cool, and the code isn't all that different. In the preceding example, simply change these
lines:
var dx = targetX - ball.x,
dy = targetY - ball.y;
So they look like this:
var dx = mouse.x - ball.x,
dy = mouse.y - ball.y;
Remember to include var mouse = utils.captureMouse(canvas) at the top of your script. You can
also remove the lines that declare the targetX and targetY variables, since you won't be needing them.
The updated document is available as 08-spring-4.html .
This is another good place to stop and play. Get a good feel for how all these variables work, and try out
many variations. Break it, and find out what breaks it. Have fun with it!
So where's the spring?
At this point, you have a very realistic-looking ball on the end of a rubber band. But it seems to be an
invisible rubber band. Well, you can fix that with a few lines of code from the canvas drawing API.
Since you have a fairly simple file without much else going on, you can safely add your drawing code
directly to the drawFrame function. In a more complex application, you might want to create another object
to hold your drawing commands and use that as a kind of drawing layer.
In each frame, after the ball is in position, you begin a new path and move the drawing cursor to the ball's
position, then, simply draw a line to current mouse position. Remember to add a stroke so that line is
visible on the canvas element:
context.beginPath();
context.moveTo(ball.x, ball.y);
context.lineTo(mouse.x, mouse.y);
context.stroke();
 
Search WWH ::




Custom Search