Falcon80 Logo
Drawing arcs on canvas

Defining an arc
You can draw arcs on canvas using the arc() method, which take in the following values:
  • (x,y) - Centre of the arc
  • r - Radius of the arc
  • startAngle - Angle from where the arc starts
  • endAngle - Angle where the arc ends and
  • A boolean value - Direction of the arc
  • 0 for clockwise
  • 1 for anticlockwise
Arc on a canvas
The startAngle and endAngle for an arc should always be in radians.

Understanding the concept of radians

A radian is defined as the angle subtended by an arc whose length is equal to its radius.
1 radian

So what does this mean?

The circumference of a circle is 2 * Pi * Radius, where Pi is constant and is equal to 3.14. This means that an arc of 1 radian can fill a circle(360 degrees) 2 * pi times or 6.28 times. Thus,

1 radian = 360 / (2 * pi)

or
1 radian = 180 / pi
or
1 radian = 57.32 degrees
2 radians = 2 * 180 / Pi or 114.64 degrees
3 radians = 3 * 180 / Pi or 171.96 degrees
6.28 radians = 6.28 * 180 / Pi or 360 degrees or a full circle

So to convert radians to degrees, multiply radians by 180/Pi.

Conversely, to convert degrees to radians, multiply degrees by pi/180

For example, 280 degrees = 280 * 3.14 / 180 = 4.88 radians.
 
Required Methods

You will need the following methods to draw an arc.
  • strokeStyle:
This method can be used to define the colour of any figure drawn on the canvas. Here, we will use it to define the colour of the arc we are about to draw.
  • arc(centrePointX, centrePointY, radius, startAngle, endAngle, direction):
This method defines the arc, with the centrepoint at (centrePointX, centrePointY), radius 'radius', startAngle in radians, endAngles in radians and direction which is a boolean value (0 = clockwise, 1 = anticlockwise).
  • stroke():
The arc() method will only define the arc. The stroke() method is the one that actually draws the arc on canvas.
  • Math.PI:
This meathod can be used instead of the constant 3.14 when converting from degrees to radians or vice versa
<html>
<head>
  <script type="application/javascript">
function init() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");

//define the colour of the circle
ctx.strokeStyle = "red";

var centreX = 200;
var centreY = 100;
var radius = 100;
var startAngle = 100 * Math.PI/180;
var endAngle = 230 * Math.PI/180;

//define the arc
ctx.arc(centreX,centreY,radius,startAngle,endAngle,false);

//draw the arc
ctx.stroke();
}
}
  </script>
</head>
<body onload="init();">
<canvas id="canvas" width="900" height="500"></canvas><br>
</body>
</html>
 
Try Code