HTML and CSS Reference
In-Depth Information
As you drag the object, it will have a new position on each frame. If you take that position and subtract the
position it was in on the previous frame, you'll know how far it moved in one frame. That's your pixels-per-
frame velocity!
Here's an example, simplifying it to a single axis. A ball is dragged, and on one frame, you note that its x
position is 150. On the next frame, you see that its x position is 170. Thus, in one frame, it was dragged 20
pixels on the x axis, and its x velocity at that point is +20. If you were to release it just then, you would
expect it to continue moving at an x velocity of 20. So, you would set
vx = 20.
This requires a few changes to the existing script. First, in the
drawFrame
function, check to see whether
the mouse is pressed, and if so, call
trackVelocity
to update the dragging velocity of the ball. You need
a couple of variables to hold the old x and y positions—call them
oldX
and
oldY
—and declare them at the
beginning of the script. This is where you store the ball's position as soon as it starts dragging:
canvas.addEventListener('mousedown', function () {
if (utils.containsPoint(ball.getBounds(), mouse.x, mouse.y)) {
isMouseDown = true;
oldX = ball.x;
oldY = ball.y;
canvas.addEventListener('mouseup', onMouseUp, false);
canvas.addEventListener('mousemove', onMouseMove, false);
}
}, false);
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
if (isMouseDown) {
trackVelocity();
} else {
checkBoundaries();
}
ball.draw(context);
}());
Then, in the
trackVelocity
function, you subtract
oldX
from the current x position and
oldY
from the
current y. This gives you the current velocity, and store these values directly in
vx
and
vy
. Next, you reset
oldX
and
oldY
to the current position of the ball again:
function trackVelocity () {
vx = ball.x - oldX;
vy = ball.y - oldY;
oldX = ball.x;
oldY = ball.y;
}
At this point, you don't need to do anything at all about the velocity. It has been kept track of all through the
drag, and the latest velocity is already stored in
vx
and
vy
. As soon as you re-enable the motion code in