How to Use HTML5 canvas arc and arcTo Functions
By Stephen Bucaro
An arc is a part of the circumference of a circle. Before I describe how to draw an arc
using the canvas arc function, I need to inform you that they take angles in radians,
not the degrees of rotation that we are all familiar with. So you should be familiar
with expressing angles in radians.
The simplest explanation for radians is that you take the length of the radius of the circle
and use that as a unit of measurement of angle around the circumference of the circle.
Now, you might be asking "why would anyone do such a thing?" Well, it ends up that the
circumference of a circle is 2PI radians (in other words approximately 6.28 times the length
of its radius). That ends up being about 57.3 degrees. Still not intuitive to most of us,
but radians really simplify the math when using calculus.
An excellent animation for explanation of what a radian is, is shown below.
The syntax of the arc function is shown below.
arc(x, y, radius, startAngle, endAngle, counterclockwise)
|x||x-coordinate of the center of the circle|
|y||y-coordinate of the center of the circle|
|radius||radius of the circle|
|startAngle||starting angle, in radians|
|endAngle||ending angle, in radians|
|counterclockwise||should the arc be drawn counterclockwise or clockwise?|
Note that the starting point (0) of rotation is the right side (3 o'clock position) of the arc's circle,
and the arc will be drawn clockwise, unless you set the optional last parameter counterclockwise
to true (false is default, and indicates clockwise).
Example code to draw an arc is shown below.
<canvas id="myCanvas" width="100" height="100" style="border:solid 1px;"></canvas>
var canvas = document.getElementById("myCanvas");
var context= canvas.getContext("2d");
// set up context
context.strokeStyle = "black";
context.lineWidth = 2;
context.arc(20, 20, 50, 0, (Math.PI/180) * 60, false);
Note in this example that, to convert degrees to radians, multiply PI/180 by the number of degrees.
So you can still think in degrees by just entering (Math.PI/180) * degress for the angle.