HTML and CSS Reference
In-Depth Information
FIguRE 5.9 When a canvas
stretches after it's finished
drawing, so do the contents of
the canvas.
Within the 2D API is a path API that allows you to move around
the canvas and draw lines or shapes. The contrived example in
Figure 5.10 shows a stick man drawn using the path API.
I won't take you through all the code used to produce the stick
man, just the highlights so you can see what methods I used. To
draw the stick man, you must specify the x, y coordinates around
the canvas that you want to draw, painstakingly specifying each
individual line. To draw the stick man head, run the following code:
ctx.beginPath();
ctx.arc(100, 50, 30, 0, Math.PI*2, true); // head
ctx.fill();
FIguRE 5.10 My contrived
stick man drawing using the
path API.
The arc, bezier, and quadratic methods use radians, so if you're used
to working with degrees, you'll need to convert them to radians. Here's
the JavaScript you need to go from degrees to radians:
var radians = degrees * Math.PI / 180;
It's also common to pass 360 degrees to the drawing methods, which
is simply Math.PI * 2 , and equally 180 degrees is Math.PI .
This gives you a solid, filled head. I've given the x, y coordinates
of 100, 50, respectively, and a radius of 30 pixels. The next argu-
ments are the start and endpoints in radians. In this example, I want
a complete circle, so I start at zero and end at Math.PI*2 , which is
equal to 360 degrees in radians. Finally the sixth argument is the
direction to draw the arc: clockwise or counterclockwise. In this
case it doesn't matter, but it's still required.

Search WWH ::

Custom Search