Draw a circle with HTML5 Canvas

HTML5 Canvas / JavaScript Graphics

June 6, 2017

Draw a circle with HTML5 Canvas

Description:

To draw a circle with HTML5 Canvas, we can create a full arc using the arc() method by defining the starting angle as 0 and the ending angle as 2 * PI.

Demo

arc()

The arc() method creates an arc/curve (used to create circles, or parts of circles).

To create a circle with arc(): Set start angle to 0 and end angle to 2*Math.PI.

Use the stroke() or the fill() method to actually draw the arc on the canvas.

Syntax:

context.arc(x,y,r,sAngle,eAngle,counterclockwise);

Parameter
x : The x-coordinate of the center of the circle.
y : The y-coordinate of the center of the circle.
r : The radius of the circle.
sAngle : The starting angle, in radians.
eAngle : The ending angle, in radians.
counterclockwise : Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise.

<!DOCTYPE HTML>
<html>
  <head>
<title>Draw Circle with HTML5 Canvas</title>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      var centerX = canvas.width / 2;
      var centerY = canvas.height / 2;
      var radius = 70;

      context.beginPath();
      context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
      context.fillStyle = 'green';
      context.fill();
      context.lineWidth = 5;
      context.strokeStyle = '#00ADEF';
      context.stroke();
    </script>
  </body>
</html>

Demo

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts

Tags

Drawing ShapesFrontend DevelopmentHTML5 Canvas

Related Posts

Many new updates happened for Android developers lately after Google I/O. Initially there was no restriction on some features but now.
phpMyAdmin is a web-based database management tool that you can use to view and edit the MySQL databases on your EC2 instance.
Title attribute can be helpful to expand on the meaning of your navigation label and give your users more context You can provide to the link.