87

There doesnt seem to be a native function to draw an oval-like shape. Also i am not looking for the egg-shape.

Is it possible to draw an oval with 2 bezier curves? Somebody expierenced with that?

My purpose is to draw some eyes and actually im just using arcs. Thanks in advance.

Solution

So scale() changes the scaling for all next shapes. Save() saves the settings before and restore is used to restore the settings to draw new shapes without scaling.

Thanks to Jani

ctx.save();
ctx.scale(0.75, 1);
ctx.beginPath();
ctx.arc(20, 21, 10, 0, Math.PI*2, false);
ctx.stroke();
ctx.closePath();
ctx.restore();
Tammo
  • 1,178
  • 1
  • 8
  • 11
  • 7
    You cannot draw an ellipse using Bezier curves, unlike some of the answers below say. You can approximate an ellipse with polynomial curves, but cannot reproduce it exactly. – Joe Aug 10 '11 at 19:50
  • I gave a +1, but this distorts the line along with the circle which doesn't work for me. Good info though. – mwilcox Jan 28 '12 at 22:03
  • 1
    @mwilcox - if you put `restore()` before `stroke()` it won't distort the line, as Johnathan Hebert mentioned in comment to Steve Tranby's answer below. Also, this is unnecessary and incorrect use of `closePath()`. Such a misunderstood method... http://stackoverflow.com/questions/10807230/what-exactly-is-a-canvas-path-and-what-is-the-use-of-ctx-closepath/16104699#16104699 – Brian McCutchon Aug 02 '13 at 02:10
  • Do not put the solution in the question post. Put solutions in answer posts. – starball Dec 19 '22 at 19:51

16 Answers16

121

updates:

  • scaling method can affect stroke width appearance
  • scaling method done right can keep stroke width intact
  • canvas has ellipse method that Chrome now supports
  • added updated tests to JSBin

JSBin Testing Example (updated to test other's answers for comparison)

  • Bezier - draw based on top left containing rect and width/height
  • Bezier with Center - draw based on center and width/height
  • Arcs and Scaling - draw based on drawing circle and scaling
  • Quadratic Curves - draw with quadratics
    • test appears to not draw quite the same, may be implementation
    • see oyophant's answer
  • Canvas Ellipse - using W3C standard ellipse() method
    • test appears to not draw quite the same, may be implementation
    • see Loktar's answer

Original:

If you want a symmetrical oval you could always create a circle of radius width, and then scale it to the height you want (edit: notice this will affect stroke width appearance - see acdameli's answer), but if you want full control of the ellipse here's one way using bezier curves.

<canvas id="thecanvas" width="400" height="400"></canvas>

<script>
var canvas = document.getElementById('thecanvas');

if(canvas.getContext) 
{
  var ctx = canvas.getContext('2d');
  drawEllipse(ctx, 10, 10, 100, 60);
  drawEllipseByCenter(ctx, 60,40,20,10);
}

function drawEllipseByCenter(ctx, cx, cy, w, h) {
  drawEllipse(ctx, cx - w/2.0, cy - h/2.0, w, h);
}

function drawEllipse(ctx, x, y, w, h) {
  var kappa = .5522848,
      ox = (w / 2) * kappa, // control point offset horizontal
      oy = (h / 2) * kappa, // control point offset vertical
      xe = x + w,           // x-end
      ye = y + h,           // y-end
      xm = x + w / 2,       // x-middle
      ym = y + h / 2;       // y-middle

  ctx.beginPath();
  ctx.moveTo(x, ym);
  ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  //ctx.closePath(); // not used correctly, see comments (use to close off open path)
  ctx.stroke();
}

</script>
Community
  • 1
  • 1
Steve T
  • 7,729
  • 6
  • 45
  • 65
  • 1
    This is the most general solution, as `scale` will distort strokes (see acdameli's answer). – Trevor Burnham Apr 17 '11 at 16:53
  • 4
    ctx.stroke() can be replace by ctx.fill() to have a filled shape. – h3xStream Dec 31 '11 at 04:43
  • 15
    scale will not distort strokes if you just scale first, then add to path using arc or whatever, then scale back to original, *then* stroke the existing path – Johnathan Hebert Jul 24 '12 at 15:47
  • How did you derive the value for kappa? – dbmikus Feb 24 '13 at 20:57
  • 1
    Just an approximation of 4*(sqrt(2)-1)/3 found many places, where Google's calc gives 0.55228475. A quick search yields this fine resource: http://www.whizkidtech.redprince.net/bezier/circle/kappa/ – Steve T Mar 09 '13 at 08:28
  • Sorry about the stupid question but, what is the x and y parameters? Is it the center of the ellipse? – Felipe Mosso Apr 09 '13 at 01:48
  • 1
    Not a stupid question. If you imagine a rectangle enclosing the ellipse then x,y is the top left corner, and the center would be at point {x + w/2.0, y + h/2.0} – Steve T Apr 11 '13 at 04:00
  • This is a great answer and one I've used in the past as well. Now (in Chrome at least) there is an actual ellipse method! http://stackoverflow.com/a/23184724/322395 – Loktar Apr 20 '14 at 16:20
  • 1
    Nice, glad to hear of ellipse canvas method. Removing closePath() and adding canvas/quadratic ellipses to the jsbin tests. – Steve T Apr 21 '14 at 00:34
48

Here is a simplified version of solutions elsewhere. I draw a canonical circle, translate and scale and then stroke.

function ellipse(context, cx, cy, rx, ry){
        context.save(); // save state
        context.beginPath();

        context.translate(cx-rx, cy-ry);
        context.scale(rx, ry);
        context.arc(1, 1, 1, 0, 2 * Math.PI, false);

        context.restore(); // restore to original state
        context.stroke();
}
Deven Kalra
  • 489
  • 4
  • 2
  • 2
    This is pretty elegant. Let `context` do the heavy lifting with `scale`. – adu Jun 12 '13 at 02:11
  • 2
    Note the very important restore *before* the stroke (otherwise the stroke width gets distorted) – Jason S Jun 02 '16 at 22:34
  • Exactly what I was looking for, thank you! I knew it was possible other than the bezier way, but I couldn't get scale to work myself. –  Oct 26 '17 at 10:37
  • @JasonS Just curious why would the stroke width get distorted if you do restore after stroke? – OneMoreQuestion Mar 28 '20 at 00:05
20

There is now a native ellipse function for canvas, very similar to the arc function although now we have two radius values and a rotation which is awesome.

ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise)

Live Demo

ctx.ellipse(100, 100, 10, 15, 0, 0, Math.PI*2);
ctx.fill();

Only seems to work in Chrome currently

Loktar
  • 34,764
  • 7
  • 90
  • 104
16

The bezier curve approach is great for simple ovals. For more control, you can use a loop to draw an ellipse with different values for the x and y radius (radiuses, radii?).

Adding a rotationAngle parameter allows the oval to be rotated around its center by any angle. Partial ovals can be drawn by changing the range (var i) over which the loop runs.

Rendering the oval this way allows you to determine the exact x,y location of all points on the line. This is useful if the postion of other objects depend on the location and orientation of the oval.

Here is an example of the code:

for (var i = 0 * Math.PI; i < 2 * Math.PI; i += 0.01 ) {
    xPos = centerX - (radiusX * Math.sin(i)) * Math.sin(rotationAngle * Math.PI) + (radiusY * Math.cos(i)) * Math.cos(rotationAngle * Math.PI);
    yPos = centerY + (radiusY * Math.cos(i)) * Math.sin(rotationAngle * Math.PI) + (radiusX * Math.sin(i)) * Math.cos(rotationAngle * Math.PI);

    if (i == 0) {
        cxt.moveTo(xPos, yPos);
    } else {
        cxt.lineTo(xPos, yPos);
    }
}

See an interactive example here: http://www.scienceprimer.com/draw-oval-html5-canvas

Andrew Staroscik
  • 2,675
  • 1
  • 24
  • 26
  • This method produces the most mathematically correct ellipse. I am wondering how it compares to the others in terms of computational cost. – Eric Rini Oct 20 '12 at 05:03
  • @Eric Just off the top of my head it looks like the difference is between (This method: 12 multiplications, 4 additions, and 8 trig functions) vs (4 Cubic Beziers: 24 multiplications and 24 additions). And that's assuming the canvas uses a De Casteljau iterative approach, I'm not sure how they're actually implemented in various browsers canvases. – DerekR Jan 07 '13 at 05:15
  • tried to profile this 2 approaches in Chrome: 4 Cubic Beziers: about 0.3 ms This method: about 1.5 ms with step = 0.1 it seems about the same 0.3ms – sol0mka Aug 21 '14 at 20:36
  • Apparently CanvasRenderingContext2D.ellipse() isn't supported on all browsers. This routine works great, perfect accuracy, good enough for [workshop templates.](http://dogfeatherdesign.com/ttn_js/) Even works on Internet Explorer, sigh. – zipzit Feb 28 '16 at 20:28
13

You could also try using non-uniform scaling. You can provide X and Y scaling, so simply set X or Y scaling larger than the other, and draw a circle, and you have an ellipse.

Community
  • 1
  • 1
Jani Hartikainen
  • 42,745
  • 10
  • 68
  • 86
12

You need 4 bezier curves (and a magic number) to reliably reproduce an ellipse. See here:

www.tinaja.com/glib/ellipse4.pdf

Two beziers don't accurately reproduce an ellipse. To prove this, try some of the 2 bezier solutions above with equal height and width - they should ideally approximate a circle but they won't. They'll still look oval which goes to prove they aren't doing what they are supposed to.

Here's something that should work:

http://jsfiddle.net/BsPsj/

Here's the code:

function ellipse(cx, cy, w, h){
    var ctx = canvas.getContext('2d');
    ctx.beginPath();
    var lx = cx - w/2,
        rx = cx + w/2,
        ty = cy - h/2,
        by = cy + h/2;
    var magic = 0.551784;
    var xmagic = magic*w/2;
    var ymagic = h*magic/2;
    ctx.moveTo(cx,ty);
    ctx.bezierCurveTo(cx+xmagic,ty,rx,cy-ymagic,rx,cy);
    ctx.bezierCurveTo(rx,cy+ymagic,cx+xmagic,by,cx,by);
    ctx.bezierCurveTo(cx-xmagic,by,lx,cy+ymagic,lx,cy);
    ctx.bezierCurveTo(lx,cy-ymagic,cx-xmagic,ty,cx,ty);
    ctx.stroke();


}
Alankar Misra
  • 151
  • 2
  • 4
  • This solution works best for me. Four parameters. Quick. Easy. – Oliver Apr 20 '15 at 12:08
  • Hello, I liked this solution as well, but when I was playing around with your code and noticed that when appending a zero to the left of the parameter value the circle is skewed. This is accentuated as the circle increases in size, do you know why this may happen? http://jsfiddle.net/BsPsj/187/ – alexcons Jun 23 '17 at 18:01
  • 1
    @alexcons prepending a 0 makes it an octal integer literal. – Alankar Misra Jul 02 '17 at 13:04
9

I did a little adaptation of this code (partially presented by Andrew Staroscik) for peoplo who do not want a so general ellipse and who have only the greater semi-axis and the excentricity data of the ellipse (good for astronomical javascript toys to plot orbits, for instance).

Here you go, remembering that one can adapt the steps in i to have a greater precision in the drawing:

/* draw ellipse
 * x0,y0 = center of the ellipse
 * a = greater semi-axis
 * exc = ellipse excentricity (exc = 0 for circle, 0 < exc < 1 for ellipse, exc > 1 for hyperbole)
 */
function drawEllipse(ctx, x0, y0, a, exc, lineWidth, color)
{
    x0 += a * exc;
    var r = a * (1 - exc*exc)/(1 + exc),
        x = x0 + r,
        y = y0;
    ctx.beginPath();
    ctx.moveTo(x, y);
    var i = 0.01 * Math.PI;
    var twoPi = 2 * Math.PI;
    while (i < twoPi) {
        r = a * (1 - exc*exc)/(1 + exc * Math.cos(i));
        x = x0 + r * Math.cos(i);
        y = y0 + r * Math.sin(i);
        ctx.lineTo(x, y);
        i += 0.01;
    }
    ctx.lineWidth = lineWidth;
    ctx.strokeStyle = color;
    ctx.closePath();
    ctx.stroke();
}
Girardi
  • 2,734
  • 3
  • 35
  • 50
5

My solution is a bit different than all of these. Closest I think is the most voted answer above though, but I think this way is a bit cleaner and easier to comprehend.

http://jsfiddle.net/jaredwilli/CZeEG/4/

    function bezierCurve(centerX, centerY, width, height) {
    con.beginPath();
    con.moveTo(centerX, centerY - height / 2);

    con.bezierCurveTo(
        centerX + width / 2, centerY - height / 2,
        centerX + width / 2, centerY + height / 2,
        centerX, centerY + height / 2
    );
    con.bezierCurveTo(
        centerX - width / 2, centerY + height / 2,
        centerX - width / 2, centerY - height / 2,
        centerX, centerY - height / 2
    );

    con.fillStyle = 'white';
    con.fill();
    con.closePath();
}

And then use it like this:

bezierCurve(x + 60, y + 75, 80, 130);

There are a couple use examples in the fiddle, along with a failed attempt to make one using quadraticCurveTo.

jaredwilli
  • 11,762
  • 6
  • 42
  • 41
  • The code looks nice, but if you use this to draw a circle by passing the same height and width values, you get a shape that resembles a square with very rounded corners. Is there a way to get a genuine circle in such a case? – Drew Noakes Oct 12 '12 at 21:34
  • I think the best option in that case would be to use the arc() method, which you can then define a start and end angle position for the arc, similar to how the top voted answer here is done. I think its the best answer overall too. – jaredwilli Oct 14 '12 at 07:12
4

Chrome and Opera support ellipse method for canvas 2d context, but IE,Edge,Firefox and Safari don't support it.

We can implement the ellipse method by JS or use a third-party polyfill.

ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise)

Usage example:

ctx.ellipse(20, 21, 10, 10, 0, 0, Math.PI*2, true);

You can use a canvas-5-polyfill to provide ellipse method.

Or just paste some js code to provide ellipse method:

if (CanvasRenderingContext2D.prototype.ellipse == undefined) {
  CanvasRenderingContext2D.prototype.ellipse = function(x, y, radiusX, radiusY,
        rotation, startAngle, endAngle, antiClockwise) {
    this.save();
    this.translate(x, y);
    this.rotate(rotation);
    this.scale(radiusX, radiusY);
    this.arc(0, 0, 1, startAngle, endAngle, antiClockwise);
    this.restore();
  }
}

ellipse 1

ellipse 2

ellipse 3

ellipse 4

cuixiping
  • 24,167
  • 8
  • 82
  • 93
  • 1
    the best answer for today. As native eclipse function is still experimental, it is absolutely awesome to have a fallback. thanks! – walv Dec 31 '17 at 03:23
4

I like the Bezier curves solution above. I noticed the scale also affects the line width so if you're trying to draw an ellipse that is wider than it is tall, your top and bottom "sides" will appear thinner than your left and right "sides"...

a good example would be:

ctx.lineWidth = 4;
ctx.scale(1, 0.5);
ctx.beginPath();
ctx.arc(20, 20, 10, 0, Math.PI * 2, false);
ctx.stroke();

you should notice the width of the line at the peak and valley of the ellipse are half as wide as at the left and right apexes (apices?).

acdameli
  • 171
  • 1
  • 4
  • 5
    You can avoid the stroke scaling if you just reverse the scale right before the stroke operation... so add the opposite scaling as the second to last line `ctx.scale(0.5, 1);` – Johnathan Hebert Feb 16 '12 at 20:18
3

Since nobody came up with an approach using the simpler quadraticCurveTo I am adding a solution for that. Simply replace the bezierCurveTo calls in the @Steve's answer with this:

  ctx.quadraticCurveTo(x,y,xm,y);
  ctx.quadraticCurveTo(xe,y,xe,ym);
  ctx.quadraticCurveTo(xe,ye,xm,ye);
  ctx.quadraticCurveTo(x,ye,x,ym);

You may also remove the closePath. The oval is looking slightly different though.

Community
  • 1
  • 1
oyophant
  • 1,294
  • 12
  • 23
3

Yes, it is possible with two bezier curves - here's a brief tutorial/example: http://www.williammalone.com/briefs/how-to-draw-ellipse-html5-canvas/

tagawa
  • 4,561
  • 2
  • 27
  • 34
  • 1
    Note that in the method given on that page, "width" isn't actually the width of the resulting ellipse. See http://stackoverflow.com/questions/5694855/bezier-curves-draw-stretched-ellipses-in-html5-canvas/5694856 – Trevor Burnham Apr 17 '11 at 16:47
2

This is another way of creating an ellipse like shape, although it uses the "fillRect()" function this can be used be changing the arguments in the fillRect() function.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Sine and cosine functions</title>
</head>
<body>
<canvas id="trigCan" width="400" height="400"></canvas>

<script type="text/javascript">
var canvas = document.getElementById("trigCan"), ctx = canvas.getContext('2d');
for (var i = 0; i < 360; i++) {
    var x = Math.sin(i), y = Math.cos(i);
    ctx.stroke();
    ctx.fillRect(50 * 2 * x * 2 / 5 + 200, 40 * 2 * y / 4 + 200, 10, 10, true);
}
</script>
</body>
</html>
aspYou
  • 21
  • 1
2

With this you can even draw segments of an ellipse:

function ellipse(color, lineWidth, x, y, stretchX, stretchY, startAngle, endAngle) {
    for (var angle = startAngle; angle < endAngle; angle += Math.PI / 180) {
        ctx.beginPath()
        ctx.moveTo(x, y)
        ctx.lineTo(x + Math.cos(angle) * stretchX, y + Math.sin(angle) * stretchY)
        ctx.lineWidth = lineWidth
        ctx.strokeStyle = color
        ctx.stroke()
        ctx.closePath()
    }
}

http://jsfiddle.net/FazAe/1/

0

Here's a function I wrote that uses the same values as the ellipse arc in SVG. X1 & Y1 are the last coordinates, X2 & Y2 are the end coordinates, radius is a number value and clockwise is a boolean value. It also assumes your canvas context has already been defined.

function ellipse(x1, y1, x2, y2, radius, clockwise) {

var cBx = (x1 + x2) / 2;    //get point between xy1 and xy2
var cBy = (y1 + y2) / 2;
var aB = Math.atan2(y1 - y2, x1 - x2);  //get angle to bulge point in radians
if (clockwise) { aB += (90 * (Math.PI / 180)); }
else { aB -= (90 * (Math.PI / 180)); }
var op_side = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)) / 2;
var adj_side = Math.sqrt(Math.pow(radius, 2) - Math.pow(op_side, 2));

if (isNaN(adj_side)) {
    adj_side = Math.sqrt(Math.pow(op_side, 2) - Math.pow(radius, 2));
}

var Cx = cBx + (adj_side * Math.cos(aB));            
var Cy = cBy + (adj_side * Math.sin(aB));
var startA = Math.atan2(y1 - Cy, x1 - Cx);       //get start/end angles in radians
var endA = Math.atan2(y2 - Cy, x2 - Cx);
var mid = (startA + endA) / 2;
var Mx = Cx + (radius * Math.cos(mid));
var My = Cy + (radius * Math.sin(mid));
context.arc(Cx, Cy, radius, startA, endA, clockwise);
}
Grant
  • 11
  • 1
0

If you want the ellipse to fully fit inside a rectangle, it's really like this:

function ellipse(canvasContext, x, y, width, height){
  var z = canvasContext, X = Math.round(x), Y = Math.round(y), wd = Math.round(width), ht = Math.round(height), h6 = Math.round(ht/6);
  var y2 = Math.round(Y+ht/2), xw = X+wd, ym = Y-h6, yp = Y+ht+h6, cs = cards, c = this.card;
  z.beginPath(); z.moveTo(X, y2); z.bezierCurveTo(X, ym, xw, ym, xw, y2); z.bezierCurveTo(xw, yp, X, yp, X, y2); z.fill(); z.stroke();
  return z;
}

Make sure your canvasContext.fillStyle = 'rgba(0,0,0,0)'; for no fill with this design.

StackSlave
  • 10,613
  • 2
  • 18
  • 35