HTML5 Canvas Element - Drawing a Circle


In the previous page we saw how to draw a line. There are several methods available for canvas. We will not take up the next method - arc. Circle is a special case of arch when the arch sweeps the full 360 degrees/ .

The following code will draw a full arch which will look like a cicle.

<!DOCTYPE html5>
<html>
<body>

<canvas id ="canvas1" width="300" height="200" style="border:2px solid #FF0000;">
</canvas>

<script>
var c1=document.getElementById("canvas1");
var context1=c1.getContext("2d");

context1.beginPath();
context1.arc(100,80,50,0, 2*Math.PI);
context1.stroke();
</script>

</body>
</html>



Try this example Online


Try this example online here. [ It opens in a new tab / windows, so you can come back ] and try to make some changes in the coordinates of the two end points of the line to see how it looks like.

Congratulations !!! You have been able to draw a circle on the Canvas in HTML5.

Some Explanation



The method beginPath() is used to declare that we are about to draw a new path. ( Although the program may still work, it is a good idea to include it).

context1.beginPath(); 


An arc is defined as

arc(x,y,r,StartAngle,StopAngle); 


Where,

x,y => Center of the circle
r= radius of the circle
StartAngle = Starting Angle of the Arc in Radian ( not degree)
StopAngle = End Angle of the Arc in Radian ( not degree)
The Arc is drawn in counterclockwise fashion. To draw a semicircle, for example, you could use
context1.arc(100,80,50,0, 1*Math.PI);