HTML and CSS Reference
In-Depth Information
Now if you open up the
advert.html
file in your web browser, you should see a line between the two lines of
text, as shown in Figure 14-5.
Figure 14-5
Drawing lines onto a canvas.
Drawing Circles
The Canvas API only provides native functions for creating rectangular shapes. To create circles, you actually need
to create a circular path that you can then stroke and/or fill, depending on your requirements. To create a circular
path, use the
arc()
function:
arc(x,y,radius,startAngle,endAngle,anticlockwise);
The
arc()
function takes five parameters. The
x
and
y
parameters specify the position of the circle's center. The
radius
parameter explains itself. The
startAngle
and
endAngle
parameters are used to specify the start and
endpoint of the arc. These values should be given in radians, not degrees. The
anticlockwise
parameter takes a
Boolean value that specifies whether the arc should be drawn anticlockwise (
true
) or clockwise (
false
).
To convert degrees to radians in JavaScript, use the following statement:
var radians = (Math.PI / 180) * degrees;
As you are creating a path, you need to make sure that you call the
beginPath()
function before you draw your
arc. Here is a small example of how you might draw a circle using the
arc()
function (this assumes that you have
already set up the canvas and a 2D drawing context):
ctx.beginPath();
ctx.arc(50, 50, 50, 0, Math.PI*2, true);
ctx.fill();
This code would draw a circle like the one shown in Figure 14-6.