HTML and CSS Reference
In-Depth Information
}
ball.draw(context);
}());
};
</script>
</body>
</html>
This exercise expands the easing formula a bit to first calculate the distance, since you'll need this to see
whether easing should be stopped. Perhaps now you can see why you need to use the absolute value of
dx . If the ball were to the right of the target, dx would be a negative number, the statement if(dx < 1)
would evaluate as true , and that would be the end of things. By using Math.abs , you make sure that the
actual distance is less than 1. You then place the ball where it is trying to go and disable the motion code.
Each animation frame request is stored in the variable animRequest . When we want to turn off the
animation loop, we pass this variable as a parameter to window.cancelRequestAnimationFrame . If this
function is not available in your browser natively, then add this cross-browser implementation to the file
utils.js :
if (!window.cancelRequestAnimationFrame) {
window.cancelRequestAnimationFrame = (window.cancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
window.clearTimeout);
}
Remember that if you are doing something like a drag-and-drop with easing, you'll want to re-enable the
motion code when the ball is dropped.
A moving target
In the examples so far, the target point has been a single, fixed location, but that's not a requirement. The
distance is calculated on each frame, and the velocity is then calculated based on that. The code doesn't
care whether or not it reaches the target, or if the target keeps moving. It just goes merrily along,
wondering what the target, distance and velocity are for every frame.
You can easily make the mouse an easing target. Just plug in the mouse coordinates ( mouse.x and
mouse.y ) where you had targetX and targetY before. Here's a version that does just that ( 04-ease-to-
mouse.html ):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Ease to Mouse</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
 
Search WWH ::




Custom Search