HTML and CSS Reference
In-Depth Information
For our purposes, the t value will be increased by the speed at which we want the object
to move. You will notice, though, that this value does not easily equate to the speed
values we used elsewhere in this chapter. The reason is that the t value was not created
with movement over time for animation in mind. The speed we specify must be smaller
than 1 so the movement on the curve will be incremental enough for us to see it as part
of the animation. For our example, we will increase t by a speed of .01 , so that we will
see 100 points on the movement curve (1/100 = .01). This is advantageous because we
will know our object has finished moving when the t value is equal to 1 .
For Example 5-11 ( CH5EX11.html ), we will start by creating the four points of the
Bezier curve in the canvasApp() function:
var p0 = {x:60, y:10};
var p1 = {x:70, y:200};
var p2 = {x:125, y:295};
var p3 = {x:350, y:350};
We then create a new ball object with a couple differing properties from those in the
other examples in this chapter. The speed is .01 , which means the object will move 100
points along the curve before it is finished. We start the t value at 0 , which means the
ball will begin at p0 :
var ball = {x:0, y:0, speed:.01, t:0};
Next, in the drawScreen() function, we calculate the Bezier curve coefficient values
( ax , bx , cx , ay , by , cy ) based on the four points ( p0 , p1 , p2 , p3 ):
var cx = 3 * (p1.x - p0.x)
var bx = 3 * (p2.x - p1.x) - cx;
var ax = p3.x - p0.x - cx - bx;
var cy = 3 * (p1.y - p0.y);
var by = 3 * (p2.y - p1.y) - cy;
var ay = p3.y - p0.y - cy - by;
Then, we take our t value and use it with the coefficients to calculate the x and y values
for the moving object. First, we get the t value from the ball object, and store it locally
so we can use it in our calculations:
var t = ball.t;
Next, we add the speed to the t value so that we can calculate the next point on the
Bezier path:
ball.t += ball.speed;
Then, we use the t value to calculate the x and y values ( xt , yt ) using the Bezier curve
equations:
var xt = ax*(t*t*t) + bx*(t*t) + cx*t + p0.x;
var yt = ay*(t*t*t) + by*(t*t) + cy*t + p0.y;
We add the speed to the t value of ball , then check to see whether t is greater than 1 .
If so, we don't increase it any further because we have finished moving on the curve:
Search WWH ::




Custom Search