Drawing Shapes Using HTML5 Canvas - Part 3: Drawing Circles
In this lesson we will continue the series on how to use the HTML5 Canvas to drawn shapes. I will show you how to draw a circle using the HTML Canvas. The process relies on a little bit of mathematical knowledge.
In Part 2 of this series we considered how coordinates are referenced i.e. starting with (0, 0) at the top left hand side of the canvas, with the positive direction being horizontally to the right and down the canvas.
To draw a circle all we need to do is give the location of the centre of the circle and the start and finish angles as follows:
arc(x-ordinate, y-ordinate, radius, start angle, end angle)
To draw a circle with centre (100, 80) and a radius of 50 the full code would look something like this:
Line 18: You will notice that the angles are given in radians. The starting position is at the 3 o’clock position and will rotate in a clockwise direction through 2 Pi radians i.e. a full circle.
It may help to look at a drawing of a circle with the angles marked.
HOW TO DRAW A SEMI-CIRCLE USING HTML CANVAS
Drawing a semi-circle can be achieved by specifying the start and end angles. Taking the previous example, if we wanted to start at the 6 o’clock position and draw a semi-circle then we would use:
HOW TO DRAW AN ARC IN AN ANTI-CLOCKWISE DIRECTION USING HTML CANVAS
By default the arc is drawn in a clockwise direction but we can specify an additional parameter to draw in an anti-clockwise direction as follows:
If the last parameter is set to true then the arc will be drawn in an anti-clockwise direction. If set to false then it will be drawn in a clockwise direction. Note that the default direction is clockwise so there is no need to include the parameter.
HAS THIS ARTICLE BEEN USEFUL ?
Has this article been useful? Then consider making a small donation now to help support this site. Your donation will go towards the running costs associated with the site. You can have your name listed as a page sponsor, if you wish!
HOW TO DRAW A FILLED CIRCLE USING THE HTML CANVAS
To draw a solid circle then all you need to do is add the fill() function as follows:
HOW TO CHANGE THE FILL COLOR OF A HTML CANVAS CIRCLE
If you would like to change the full color then simply use the fillStyle function as follows: