HTML and CSS Reference
In-Depth Information
Once the head is drawn, I want to draw a face. The eyes
and smile will be in red (well, grey in the figure). When I draw
the facial features, I need to use beginPath again. Figure 5.11
shows what the result would be if I didn't use beginPath . This
is because the previous arc line I drew would be included in
the final face path, and because I'm starting a new arc for the
mouth, as you'll see in the following code listing. I could fix the
line joining the edge of the head to the mouth by using moveTo ,
which is effectively lifting the pen from the canvas to begin
drawing someplace else, but I don't want the coloured outline
around the head.
// draw the smile
ctx.strokeStyle = '#c00';
ctx.lineWidth = 3;
ctx.arc(100, 50, 20, 0, Math.PI, false);
The previous code listing gives me a nice semicircle for the
smile with a new stroke colour and width. For the head I used
fill , but for the face I need to use stroke , which will draw the
line rather than a solid shape. Next the eyes:
ctx.fillStyle = '#c00';
// start the left eye
ctx.arc(90, 45, 3, 0, Math.PI*2, true);
ctx.moveTo(113, 45);
// draw the right eye
ctx.arc(110, 45, 3, 0, Math.PI*2, true);
ctx.stroke(); // thicker eyes
I started a new path again, which means I can start drawing the
arc for the eyes without using moveTo (as I did when making the
smile). However, once I filled the arc, creating a solid-looking eye,
I lift the pen with moveTo(113, 45) to draw the right eye. Notice
that I moved to the right by the arc's first x coordinate plus the
radius value to create a solid line, which ensures that the starting
point of the arc matches where I put the pen down. Finally I use
the stroke method to give the eyes a bit more thickness.
The code goes on to move the drawing point around and finally
end up with an image of our stick man.
FIguRE 5.11 An example of
how a continued path causes
an error in the final drawing.
Search WWH ::

Custom Search