To create circles (arcs) onto the HTML5 Canvas, we can use the arc()
method. Arcs are defined by a center point, radius, starting angle, ending angle, and the arc drawing direction. The canvas element and arc()
method is supported by Internet Explorer 9, Firefox, Opera, Chrome, and Safari. In this first example, we will draw a circle.
In instances where you need to draw a semi-circle, or a custom arc, you can use the same method. An arc is simply a section of the circumference of a circle. So, we can define this arc by a starting point (x
, y
), radius, and starting and ending points on the perimeter of the circle.
Finally, we pass an optional parameter in the arc()
method to indicate the path between the endpoints. The default value for this parameter is false
, which is the equivalent to “clockwise”.
Syntax
context.arc(x,y,radius,startAngle,endEngle,counterclockwise);
Parameter | Description |
---|---|
x | The circle’s X coordinate. |
y | the circle’s Y coordinate. |
radius | The radius of the circle. |
startAngle | The starting angle in radians. |
endAngle | The ending angle in radians. |
counterClockwise | Optional parameter. Default is false . |
Example
<canvas id="myCanvas" width="400" height="200">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.beginPath();
context.arc(200, 100, 50, 0, 2 * Math.PI);
context.stroke();
</script>
We can use some of the other properties and methods to modify other properties of this shape. We can also adjust the parameters of the arc()
method to make a semi-circle.
Also, you should note that the closePath()
method is included so that the semi-circle becomes a closed shape.
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.beginPath();
context.arc(200, 150, 100, 1 * Math.PI, 2 * Math.PI);
context.closePath();
context.fillStyle = '#FFAA00';
context.fill();
context.lineWidth = 6;
context.strokeStyle = '#7F7F7F';
context.stroke();
</script>