Ellipse
suggest changeNote: Browsers are in the process of adding a built-in context.ellipse drawing command, but this command is not universally adopted (notably not in IE). The methods below work in all browsers.
Draw an ellipse given its desired top-left coordinate:
// draws an ellipse based on x,y being the top-left coordinate
function drawEllipse(x,y,width,height){
var PI2=Math.PI*2;
var rx=width/2;
var ry=height/2;
var cx=x+rx;
var cy=y+ry;
var increment=1/Math.max(rx,ry);
ctx.beginPath();
ctx.moveTo(cx+rx, cy);
for(var radians=increment; radians<PI2; radians+=increment){
ctx.lineTo(cx+rx*Math.cos(radians), cy-ry*Math.sin(radians));
}
ctx.closePath();
ctx.stroke();
}
Draw an ellipse given its desired center point coordinate:
// draws an ellipse based on cx,cy being the ellipse's centerpoint coordinate
function drawEllipse2(cx,cy,width,height){
var PI2=Math.PI*2;
var rx=width/2;
var ry=height/2;
var increment=1/Math.max(rx,ry);
ctx.beginPath();
ctx.moveTo(cx+rx, cy);
for(var radians=increment; radians<PI2; radians+=increment){
ctx.lineTo(cx+rx*Math.cos(radians), cy-ry*Math.sin(radians));
}
ctx.closePath();
ctx.stroke();
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents