To create a circle, you can follow a similar process to how you created a square. The main difference lies in using the
arc(x, y, r, startAngle, endAngle)
method. When drawing a circle, set the
startAngle
and
endAngle
to 0 and 2pi respectively. For example, to draw a circle at coordinates (100,100) with a radius of 10:
ctx.beginPath();
ctx.arc(100, 100, 10, 0, Math.PI*2);
ctx.fill(); // Use fill() to fill the circle; stroke() for an empty circle.
Following a similar coding style as before, you can create a Circle
. The approach is nearly identical. Here's a snippet showcasing this:
var ctx = document.getElementById("canvas").getContext("2d");
//Create Var
var circ = new Circle(100, 100, 20);
//Define the circle
function Circle(x, y, r) {
"use strict";
this.x = (x === null) ? 0 : x;
this.y = (y === null) ? 0 : y;
this.r = (r === null) ? 0 : r;
this.fill = function(ctx) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI*2);
ctx.fill();
}
}
//Draw the circle as an object
circ.fill(ctx);
canvas{ border: 1px solid black; }
<canvas width=200 height=200 id="canvas"></canvas>