HTML5 Game - Drawing an Arc Using the arc() Method

Introduction

To draw an arc on a canvas, you use the drawing context's arc() method.

The general syntax of arc() is as follows:

context.arc(x, y, radius, start_angle, end_angle, direction) 

The first two parameters of the arc() method indicate the coordinates of the center of the arc.

The radius parameter indicates the arc's radius.

The start and end angles are the angles in radians for the start point and end point of the arc, respectively.

The direction parameter indicates whether the arc should be drawn in a clockwise or counterclockwise direction.

The following code shows a code fragment that draws an arc using the arc() method.

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html lang="en">
 <head> 
  <meta charset="UTF-8"> 
  <title>HTML5 Canvas</title> 
  <script type="text/javascript">
    window.onload = function(){//from ww  w.  j a v  a  2  s. c om
        let canvas = document.getElementById("myCanvas");
        let context = canvas.getContext("2d");
        // draw stuff here
        let x = canvas.width / 2; 
        let y = canvas.height / 2; 
        let radius = 100; 
        let start_angle = 0.5 * Math.PI; 
        let end_angle = 1.75 * Math.PI; 
        context.arc(x, y, 75, start_angle, end_angle, false); 
        context.lineWidth = 20; 
        context.stroke(); 

        
    };
</script> 
 </head> 
 <body> 
  <canvas id="myCanvas" width="300" height="200"></canvas>   
 </body>
</html>

Note

This code above calculates the center of the canvas.

And then uses those coordinates as the x and y coordinates of the arc.

The start and end angles are calculated in radians using the Math.PI constant.

The direction parameter is set to false, indicating that the arc should be drawn in the clockwise direction.

Related Topic