HTML and CSS Reference
In-Depth Information
The arc() and arcTo() methods discussed in this section are very useful for drawing circles, sectors,
and rounded rectangles.
Drawing Paths
In the preceding sections, you learned to draw lines and curves. You can combine lines and curves to draw
a path or a shape. Simply put, a path is a sequence of drawing operations that result in a shape. A path can
be open or closed. A closed path can also be filled with some color or pattern.
To draw a path, you first call the beginPath() method and then draw lines or curves as before. To flag
the end of the path, you call stroke() (to draw the outline of a shape) or ill() (to draw a filled shape).
Listing 4-7 draws a smiley using the moveTo() and arc() methods.
Listing 4-7. Drawing a Smiley
var canvas = $("#MyCanvas").get(0);
var context = canvas.getContext("2d");
context.arc(100, 100, 80, 0, Math.PI * 2, false);
context.moveTo(160, 100);
context.arc(100, 100, 60, 0, Math.PI, false);
//left eye
context.moveTo(75, 70);
context.arc(65, 70, 10, 0, Math.PI * 2, true);
//right eye
context.moveTo(135, 70);
context.arc(125, 70, 10, 0, Math.PI * 2, true);
context.lineWidth = 5;
In all, there are four calls to the arc() method: they draw the outline of the face, the smile, the left eye,
and the right eye, respectively. To actually draw the path, the code calls the stroke() method— stroke()
draws the outline of the path. Figure 4-10 shows what the smiley looks like in the browser.
You can also draw closed paths that are filled by a color. For example, Listing 4-8 draws a triangle that
is filled with blue color.
Listing 4-8. Drawing a Filled Shape
context.lineTo(150, 100);
context.lineWidth = 10;
context.strokeStyle = 'red';
context.fillStyle = 'blue';
Search WWH ::

Custom Search