An easy technique for ellipsis drawing on JavaScript canvas objects

doug
Wed, 25 Feb 2009 17:08:52 +0000

During my recent struggle with the JavaScript canvas object I was looking for a method to draw ellipses. Originally I was trying to use the arcTo() and even got desperate enough to have a quick play around with the bezierCurveTo() and quadraticCurveTo( ) functions before the obvious solution dawned on me.

In the event anybody else wastes their times looking for a way to do this try the following:

var e = document.createElement("canvas");
document.body.appendChild(e);

var context = e.getContext("2d");

context.fillStyle = "orange";
context.lineWidth = 1;

context.scale(2, 1);
context.arc(e.width / 4, e.height / 2, (e.width/ 4) - 2, 0, Math.PI * 2, true);
context.fill();
context.scale(1, 1);

context.strokeStyle = "black";

context.stroke();

See what I did there? I used a standard arc() (which is a function that essentially draws a circle) and adjusted the coordinate system using the scale() function. The arguments (2, 1) basically say that every x coordinate rendered should be multipled by 2. This essentially "stretches" the drawing of the objects. Afterwards I call scale() again with the arguments (1, 1) to restore it to it's original coordinate system.

Note that although this works wonderfully for filled ellipses, those with a stroke should be aware that it stretches the line width of the stroke too. This is more visible with thicker lineWidths.