How to draw a simple circle in HTML5 Canvas using minimum JavaScript code?
5 Answers
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)
First of all, you need to get the canvas context:-
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
Now let us define the position and radius:-
const X = canvas.width / 2;
const Y = canvas.height / 2;
const radius = 45;
Now let us set the color and line width:-
ctx.lineWidth = 3;
ctx.strokeStyle = '#FF0000';
Now, to draw the circle, we have to use the arc method and set the angle to 2 X π
ctx.beginPath();
ctx.arc(X, Y, radius, 0, 2 * Math.PI, false);
ctx.stroke();
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>
Base on Sam's answer, I combined all the parameters into one object so that it is more readable when using the function.
function drawCircle(obj) {
obj.ctx.beginPath();
obj.ctx.arc(obj.x, obj.y, obj.radius, 0, 2 * Math.PI, false);
if (obj.fill) {
obj.ctx.fillStyle = obj.fill;
obj.ctx.fill();
}
if (obj.stroke) {
obj.ctx.lineWidth = obj.strokeWidth;
obj.ctx.strokeStyle = obj.stroke;
obj.ctx.stroke();
}
}
To use:
let ctx = canvas.getContext('2d');
drawCircle({
ctx: ctx,
x: 100,
y: 100,
radius: 20,
fill: "green",
});