The ctx.arc(cx, cy, radius, startAngle, endAngle, drawInverse) method is useful for drawing arcs of circles. The parameters it takes are the center of the circle/arc, its radius, the starting angle of the arc (clockwise from 3 o'clock), the ending angle of the arc, and an optional parameter we will talk about presently.
Note: the figures in this page have been borrowed from the HTML5 Canvas Tutorials Web site.
Typical usage for drawing an arc/circle/ellipse is:
ctx.arc(centerX, centerY, radius, startAngle, endAngle); // clockwise drawing
ctx.arc(centerX, centerY, radius, startAngle, endAngle, false);
The angles are in radians (between 0 and 2*Math.PI). The arc is drawn clockwise. Beware that this may not seem natural if you're used to the trigonometric order.
The last parameter is optional and has a value of false by default. If true, instead of drawing an arc of circle that corresponds to the parameters, it will draw its complement. See the examples below to see the difference.
Try this example:
Code source extract:
ctx.beginPath();
// we ommited the last parameter
ctx.arc(100, 75, 50, 0, Math.PI/2);
ctx.lineWidth = 10;
ctx.stroke();
And if we change the last parameter of the arc function call (line 3) to true (we omitted it, so it took a value of false by default) :
ctx.beginPath();
// we omitted the last parameter
ctx.arc(100, 75, 50, 0, Math.PI/2, true);
ctx.lineWidth = 10;
ctx.stroke();
Then, the result is the "complement" of the previous arc:
Source code:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 70;
ctx.beginPath();
// Add to the path a full circle (from 0 to 2PI)
ctx.arc(centerX, centerY, radius, 0, 2*Math.PI, false);
// With path drawing you can change the context
// properties until a call to stroke() or fill() is performed
ctx.fillStyle = "lightBlue";
// Draws the filled circle in light blue
ctx.fill();
// Prepare for the outline
ctx.lineWidth = 5;
ctx.strokeStyle = "black";
// draws the path (the circle) AGAIN, this
// time in wireframe
ctx.stroke();
// Notice we called ctx.arc() only once ! And drew it twice
// with different styles
Notice that we called ctx.arc() only once! And drew it twice, with different styles, with calls to ctx.stroke() and ctx.fill(). Each call drew the defined path in the wireframe and filled modes, respectively!