Online Book Reader

Home Category

HTML5 Canvas [85]

By Root 6543 0
path

points.push({x:xt,y:yt});

for (var i = 0; i< points.length; i++) {

context.drawImage(pointImage, points[i].x, points[i].y,1,1);

}

context.closePath();

player.x = xt-bullseye.width/2;

player.y = yt-bullseye.height/2;

context.drawImage(bullseye,player.x,player.y);

}

var p0 = {x:60, y:10};

var p1 = {x:150, y:350};

var p2 = {x:300, y:375};

var p3 = {x:400, y:20};

var player = {x:0, y:0, speed:.01, t:0};

var points = new Array();

theCanvas = document.getElementById("canvasOne");

context = theCanvas.getContext("2d");

setInterval(drawScreen, 33);

}

Your browser does not support HTML5 Canvas.

Creating a Cubic Bezier Curve Loop


You can create some very interesting paths using the four points in a cubic Bezier curve. One such effect is a loop. To create a loop, you need to make sure the points form an X, with p0 diagonal from p1, and p2 and p3 on an opposite diagonal from the other two points. p0 and p3 must be closer to the center of the canvas than p1 or p2. Below are the points we will use to create this effect in Example 5-13:

var p0 = {x:150, y:440;

var p1 = {x:450, y:10};

var p2 = {x:50, y:10};

var p3 = {x:325, y:450};

Since it is much easier to show than tell when it comes to cubic Bezier curves, look at Figure 5-16. It shows what the looping curve looks like when Example 5-13 is executed in a web browser.

NOTE

This effect can only be created with the four points of a cubic Bezier curve. There is also a three-point Bezier curve known as a quadratic Bezier curve. You cannot create loops or S curves with quadratic Bezier curves because the three points are not as precise as the four points of a cubic Bezier curve.

Figure 5-16. Moving an object in a loop using a cubic Bezier curve

Since the code for this example is essentially the same as in Example 5-12 (besides the four points), we have highlighted in bold the changed code in Example 5-13. We have done this to show you that—with relatively simple changes—you can create dramatic animation effects using cubic Bezier curves.

Example 5-13. Bezier curve loop

CH5EX13: Bezier Curve Loop