Categories
JavaScript Answers

How to Draw a Circle in HTML5 Canvas Using JavaScript?

Spread the love

To draw a circle in HTML5 canvas using JavaScript, we can use the arc method.

For instance, we can add the canvas element by writing:

<canvas style='width: 300px; height: 300px'></canvas>

Then we write:

const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 70;
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();

We select the canvas with document.querySelector.

Then we get the canvas context with getContext.

Next, we set the center’s coordinates with centerX and centerY.

We then we set the radius of the circle.

Next, we call beginPath to start drawing.

Then we call arc with centerX, centerY, radius, 0, 2 * Math.PI and `false.

We need 2 * Math.PI to draw an arc forms the circle.

Next, we set the fillStyle to set the fill of the circle.

Then we call fill to draw the fill.

Next, we set lineWidth to set the outline’s width.

Then we set strokeStyle to set the outline color.

And finally, we call stroke to draw the outline.

Now we see a circle with green fill color and black outline drawn.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.