Draw a Circle in JavaScript with 2 Easy Ways

Draw a Circle in JavaScript

We can easily draw a circle using CSS but wondering if you can draw it in javascript? Let’s see how to draw a circle in Javascript.
Example output:
draw a circle in javascript

2 Ways to create a circle in JS

You can draw circles in javascript in two ways, without the canvas method and canvas method.

Canvas Method

In this method, we have to use the canvas element that provides a blank area for drawing graphics using JavaScript. Let’s see the steps:
  1. Create <canvas> element in HTML and set ID, height, and width attributes.
  2. Get a reference to the canvas element usingdocument.getElementById("IDname") in Javascript.
  3. Create a 2D drawing context with const ctx = canvas.getContext("2d"). It provides methods for drawing shapes on the canvas.
  4. Then Set the center coordinates of the circle using centerX and centerY, which are calculated as half of the canvas width and, respectively.
  5. Set strokeStyle property to specify the colors of the circle and its border, respectively.
  6. To draw the circle, you can use the ctx.beginPath() method to start the drawing path, ctx.arc() to draw the circular arc, ctx.fill() to fill the circle with the specified color, ctx.stroke() to draw the border of the circle, and ctx.closePath() to close the drawing path.
Example
<html>
<head>
  <title>Draw a Circle in JavaScript</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
</body>
<script type="text/javascript">
// Get the canvas element from the HTML file
const canvas = document.getElementById("myCanvas");

// Create a 2D drawing context
const ctx = canvas.getContext("2d");

// Set the center coordinates and the radius of the circle
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 100;

// Set the color and other properties of the circle
ctx.strokeStyle = "'dotted' black"; // Color of the circle's border (black in this case)
ctx.lineWidth = 2; // Width of the circle's border

// Draw the circle
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
ctx.stroke(); // Draws the border of the circle
ctx.closePath();

</script>
</html>

Live Demo:

READ ALSO  What is Type Casting in JavaScript | Advanced Guide

Without Canvas Method:

In this method, we have applied CSS Styles using the reference variable of the HTML <div> element in Javascript.
<html>
<head>
  <title>Draw a Circle in JavaScript</title>
</head>
<body>
<div id="myCircle"></div>
</body>


<script type="text/javascript">
  const circle = document.getElementById("myCircle");
    circle.style.width = "100px";
    circle.style.height = "100px";
    circle.style.border = "2px solid black";
    circle.style.borderRadius = "50%";
</script>
</html>

Conclusion

So in this article, we have seen how to create a circle in javascript in two ways.

Leave a Reply