Easy circles on the canvas with context.ellipse()
A while ago I was building a family tree viewer for an ACW (Assessed CourseWork) at University. Part of this ACW involved drawing faces inside ovals and using circles for various things. The suggested method here was using bezier curves (more on this on Wednesday), but I found another (much easier!) way of doing it that I thought others would find useful, so I am posting about it here.
Instead of using context.bezierCurveTo()
and battling with control points, you can just use context.ellipse
to add either a circle or an ellipse to the current path. Here's an extract fomr the wonderful MDN:
Syntax
void ctx.ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise);
Parameters
Parameter | Explanation |
---|---|
x |
The x axis of the coordinate for the ellipse's center. |
y |
The y axis of the coordinate for the ellipse's center. |
radiusX |
The ellipse's major-axis radius. |
radiusY |
The ellipse's minor-axis radius. |
rotation |
The rotation for this ellipse, expressed in radians. |
startAngle |
The starting point, measured from the x axis, from which it will be drawn, expressed in radians. |
endAngle |
The end ellipse's angle to which it will be drawn, expressed in radians. |
anticlockwise |
Optional. An Boolean which, if true, draws the ellipse anticlockwise (counter-clockwise), otherwise in a clockwise direction. |
For example, here's how you'd draw a 100x200 red ellipse at (0, 0):
function renderEllipse(context)
{
context.fillStyle = "#ff3300";
context.beginPath();
context.ellipse(0, 0, 100, 200, 0, 0, Math.PI * 2, false);
context.fill();
}
The startAngle
and endAngle
functions work the same as the context.arc()
command - they let you draw just part of a circle or ellipse instead of a full one. In the example above, I'm drawing a full one by starting at 0 and finishing at 2π
(360°).
I've built a simple 'ripples' demo that demonstrates context.ellipse()
in action. Click anywhere on the screen to create a ripple. The background is made with a few quick radial gradiants that fade from a colour into transparency.