There are three types of curves we can create in canvas—using the arc, quadratic curves, and Bezier curves. Let's get started.
If you recall in Chapter 1, Drawing Shapes in Canvas, in our first recipe we used the arc method to create perfect circles. The arc method is much more than just that. We can actually create any partial curve in a circular shape. If you don't recall drawing circles, I strongly encourage you to scan through Chapter 1, Drawing Shapes in Canvas again, and while you are there, you will find the template for creating the HTML documents as well. We are exclusively going to focus on the JavaScript code in this recipe.
Let's jump into it and create our first noncircle that has curves:
pacman
canvas element and fetch its width and height by using the following code snippet:var canvas = document.getElementById("pacman"); var wid = canvas.width; var hei = canvas.height;
radian
variable (one degree in radians):var radian = Math.PI/180;
var context = canvas.getContext("2d"); context.fillStyle = "#000000"; context.fillRect(0,0,wid,hei);
context.beginPath();
context.fillStyle = "#F3F100";
context.moveTo(wid/2,hei/2);
context.arc(wid / 2, hei / 2, 40, 40*radian, 320*radian, false);
context.lineTo(wid/2,hei/2);
context.closePath(); context.fill();
You have just created a PacMan.
For the first time, we take advantage and create a pie-type shape, known as PacMan (you can see how this can be very useful when we get into creating the pie graph). Very simple—again we connect to that idea of radians:
context.arc(wid / 2, hei / 2, 40, 40*radian, 320*radian, false);
Notice how our 4th and 5th parameters—instead of being a complete circle by starting from 0 and ending at 2*Math.PI
—are setting the angle to start the arc at radian 40 and end at radian 320 (leaving 80 degrees open to create the mouth of a PacMan ). All that is left is to start drawing from the center of the circle:
context.moveTo(wid/2,hei/2); context.arc(wid / 2, hei / 2, 40, 40*radian, 320*radian, false); context.lineTo(wid/2,hei/2);
We start by moving our pointer to the center of our circle. We then create the arc. As our arc isn't a complete shape it's continuing where we left off—drawing a line from the center of the arc to the starting point (40 degrees). We complete the action by drawing a line back to the center of the arc to complete the shape. Now we are ready to fill it and complete our work.
Now that we have got arcs out of the way, you can see how useful this will be for creating pie charts.
3.145.54.7