Online Book Reader

Home Category

HTML5 Canvas [83]

By Root 6427 0

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:

ball.t += ball.speed;

if (ball.t > 1) {

ball.t = 1;

}

Finally, when we draw the ball object on the canvas, we use the xt and yt values:

context.arc(xt,yt,5,0,Math.PI*2,true);

Figure 5-14 shows what Example 5-11 (CH5EX11.html) looks like when it is executed in a web browser. In addition to drawing the points of the path using the points array, we also draw the four points of the Bezier curve. These illustrate the relationship of the points to the curve itself. Notice that the curve does not pass through p1 or p2.

Figure 5-14. Moving a circle on a Bezier curve

Example 5-11 gives the full code listing for CH5EX11.html, including the code to draw the Bezier curve points on the canvas. You can find that code in the drawScreen() function following the //draw the points comment.

Example 5-11. Moving on a cubic Bezier curve

CH5EX11: Moving On A Cubic Bezier Curve