How to Draw a Circle Using the HTML Canvas

html5canvas.png

In this tutorial you will learn how to draw a circle using the HTML canvas.

In order to draw a circle we need to know:

  • the centre

  • the radius

  • the starting angle (in radians)

  • the finishing angle (in radians)

  • if we will be rotating clockwise or anti-clockwise

The last 3 criteria would become particularly important if we were drawing an arc (part circle).

 
circle-html-canvas.png

STEP 1

The first thing we need to do is create a canvas element on the page:

Line 8: we create the canvas with an ID of 'myCanvas' and width of 600 pixels and height of 400 pixels. 

STEP 2

Next, we reference the canvas element and set up a 2D drawing context:

Line 10: we get the canvas element called 'myCanvas' and assign it to the variable c.

Line 11: we establish a 2D drawing context on the assigned canvas c. 

STEP 3

We now draw the circle:

Line 12: The arc method takes 6 values as follows:

(x position, y position, radius, start angle, end angle, rotation direction)

In our example we have the following:

  • an x-position of 200 pixels

  • a y-position of 100 pixels

  • a radius of 40 pixels

  • a starting angle of 0 radians

  • an ending angle of 2 PI radians

  • a clockwise rotation

So, the centre of our circle is at point (200, 100) with a radius of 40 pixels.

circle1.png

Note that angles are given in radians.

The last value specifies the rotation. By default this value is set as false. In other words, if we were to omit this final value then the default would be to draw the arc in a clockwise direction. Simply think of the question 'Do you want to go in an anti-clockwise direction?'.  By setting this to false we will go in a clockwise direction.

Line 13: the circle is stroked.

STEP 4

In order to see the effect of the 6 values above it may be best to draw a quarter circle as follows:

In this example we have drawn a quarter circle starting at 0 and going in a clockwise direction. 

Line 12: A full circle is given by 2*Math.PI, hence a quarter circle is given by 0.5*Math.PI, as shown below:

circle2.png