canvas has APIs to draw circles and arcs:
arc(x, y, radius, startAngle, endAngle, anticlockwise): Draws an arc that is centered at (x, y) position with radius r starting at
startAngle and ending at
endAngle, going in the given direction indicated by
anticlockwise (defaulting to clockwise).
arcTo(x1, y1, x2, y2, radius): Draws an arc with the given control points and radius, connected to the previous point by a straight line.
Note: The radius is in radians, not degrees. degrees should be converted to radians or the APIs will take it as rads. We can convert degrees to radians with this algorithm: .
In the methods above, are the center position of the circle/arc on the
radius is the radius of the circle/arc.
startAngle is the angle (in radians) where the drawing of the circle/arc will start.
endAngle is the angle (in radians) where the tracing of the circle/arc would stop.
antiClockWise is the direction of the circle/arc tracing. If
true, the circle/arc is drawn anti-clockwise; otherwise, clockwise.
Since the methods are all arcs, drawing a circle with them is a little tricky.
const degToRad = (degrees) => (Math.PI / 180) * degrees context.arc(100, 100, 50, degToRad(0), degToRad(360), true) context.stroke()
This will draw a circle.
We set the center of the circle to start at = , with a radius of . We set the starting angle at degrees (we use the
degToRag function to convert degrees to radians) and the stop angle at degrees to make the complete circle. Then, the argument
true makes the code trace the circle from the anticlockwise direction. The
stroke() method draws out the outline of the circle.
Let’s fill the circle through the
context.arc(100, 100, 50, degToRad(0), degToRad(360), true) context.fill()
We can draw an arc from to :
context.arc(100, 100, 50, degToRad(0), degToRad(180), true) context.stroke()
This will draw an arc:
This is because we start at angle and stop at . If we change to , the code will draw a circle.
Now, let’s make a filled arc:
context.arc(100, 100, 50, degToRad(0), degToRad(180), true) context.fill()
View all Courses