How to draw a circle in HTML5 Canvas using JavaScript?
I took the answers above and turned them into a useful function:
function drawCircle(ctx, x, y, radius, fill, stroke, strokeWidth) {
ctx.beginPath()
ctx.arc(x, y, radius, 0, 2 * Math.PI, false)
if (fill) {
ctx.fillStyle = fill
ctx.fill()
}
if (stroke) {
ctx.lineWidth = strokeWidth
ctx.strokeStyle = stroke
ctx.stroke()
}
}
Then, use it like so to draw a black circle with a red stroke (width 2) at coordinates 50,50, with radius 25:
let ctx = canvas.getContext('2d')
drawCircle(ctx, 50, 50, 25, 'black', 'red', 2)
Here is how to draw a circle using JavaScript in HTML5:
const canvas = document.getElementById('myCanvas');
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();
body {
margin: 0;
padding: 0;
}
<canvas id="myCanvas" width="578" height="200"></canvas>