Drawing arcs and circles with the HTML5 canvas

This tutorial explains how to use the HTML5 canvas and JavaScript to draw circles and arcs on the canvas. The code below shows how to draw a full circle, but you can easily modify it to draw arcs (the circle is made up of arcs).

In this example, the circle will be inside a canvas with a black border and will look like this:

Screen Shot 2015-03-12 at 10.47.58 am

Watch the video below and then scroll down to see the sample code.

Refer to the comments in the code to find out what is happening on each line of the code.

<!DOCTYPE html>
<html>
<head>
 <title>Arcs and circles</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
</head>
<body>
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.arc(150,150,100,0,Math.PI*2,false); // x, y, radius, startAngle, endAngle, true/false (for clockwise and anticlockwise)
 // Math.PI gives semi-circle
 // Math.PI*2 gives full circle
 // Numbers can also be used instead of Math.P eg. 6.28
 // try using numbers less than 6.28 to see how you get less of a circle
 ctx.stroke();
 //try doing semi-circle that is (flipped over) by chaning false to true
 
 }
 window.onload = draw;
 </script>
 
 <canvas id="myCanvas" width="500" height="350">
</body>
</html>

Next tutorial: Drawing arcs using the arcTo method