HTML and CSS Reference
In-Depth Information
Even though the ball on the canvas is not getting any closer visually, mathematically it will still never
actually reach its target. So, if you're doing a simple comparison, as in the previous example, your easing
code will never get shut off. What you need to decide is: “How close is close enough?” This is determined
by whether the distance to the target is less than a certain amount. For many examples in this topic, if an
object is within a pixel of its target, it's safe to say it has arrived, and the easing code will be turned off.
If you are using two dimensions, you can calculate the distance using the formula introduced in Chapter 3:
var distance = Math.sqrt(dx * dx + dy * dy);
If you have a single value for distance, as when you are moving an object on a single axis, you need to
use the absolute value of that distance, as it may be negative. You can do this by using the Math.abs
method.
Here's a simple example to demonstrate turning off easing ( 03-easing-off.html ):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Easing Off</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<textarea id="log"></textarea>
<script src="utils.js"></script>
<script src="ball.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
log = document.getElementById('log'),
ball = new Ball(),
easing = 0.05,
targetX = canvas.width / 2,
animRequest;
ball.y = canvas.height / 2;
(function drawFrame () {
animRequest = window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
var dx = targetX - ball.x;
if (Math.abs(dx) < 1) {
ball.x = targetX;
window.cancelRequestAnimationFrame(animRequest);
log.value = "Animation done!";
} else {
var vx = dx * easing;
ball.x += vx;
Search WWH ::




Custom Search