How to draw a circle in HTML5 Canvas using JavaScript?
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: 0px;
padding: 0px;
}
<canvas id="myCanvas" width="578" height="200"></canvas>
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)
Creating shapes is easier using new Canvas Path2D, which uses the same canvas drawing API, and allow separation of the declaration from drawing itself, and reuse of complex geometry:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 70;
let circle = new Path2D(); // <<< Declaration
circle.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'blue';
context.fill(circle); // <<< pass circle to context
context.lineWidth = 10;
context.strokeStyle = '#000066';
context.stroke(circle); // <<< pass circle here too
body {
margin: 0px;
padding: 0px;
}
<canvas id="myCanvas" width="578" height="200"></canvas>