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();
4
  • 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
    Commented Aug 10, 2011 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
    Commented Jan 28, 2012 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... stackoverflow.com/questions/10807230/… Commented Aug 2, 2013 at 2:10
  • Do not put the solution in the question post. Put solutions in answer posts.
    – starball
    Commented Dec 19, 2022 at 19:51

16 Answers 16

122

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>
9
  • 1
    This is the most general solution, as scale will distort strokes (see acdameli's answer). Commented Apr 17, 2011 at 16:53
  • 4
    ctx.stroke() can be replace by ctx.fill() to have a filled shape.
    – h3xStream
    Commented Dec 31, 2011 at 4: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 Commented Jul 24, 2012 at 15:47
  • 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: whizkidtech.redprince.net/bezier/circle/kappa
    – Steve T
    Commented Mar 9, 2013 at 8:28
  • 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
    Commented Apr 11, 2013 at 4:00
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();
}
4
  • 2
    This is pretty elegant. Let context do the heavy lifting with scale.
    – adu
    Commented Jun 12, 2013 at 2:11
  • 2
    Note the very important restore before the stroke (otherwise the stroke width gets distorted)
    – Jason S
    Commented Jun 2, 2016 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.
    – user4051844
    Commented Oct 26, 2017 at 10:37
  • @JasonS Just curious why would the stroke width get distorted if you do restore after stroke? Commented Mar 28, 2020 at 0:05
21

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

3
  • 2
    Yeah, the implementation of this one is slow.
    – user1693593
    Commented Apr 20, 2014 at 16:42
  • @Epistemex Agreed. I imagine/hope it will get faster over time.
    – Loktar
    Commented May 2, 2014 at 16:34
  • 1
    According to developer.mozilla.org/en-US/docs/Web/API/…, it is supported in Opera as well now
    – jazzpi
    Commented Dec 26, 2014 at 15:24
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

4
  • This method produces the most mathematically correct ellipse. I am wondering how it compares to the others in terms of computational cost.
    – Eric Rini
    Commented Oct 20, 2012 at 5: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
    Commented Jan 7, 2013 at 5: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
    Commented Aug 21, 2014 at 20:36
  • Apparently CanvasRenderingContext2D.ellipse() isn't supported on all browsers. This routine works great, perfect accuracy, good enough for workshop templates. Even works on Internet Explorer, sigh.
    – zipzit
    Commented Feb 28, 2016 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.

0
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();


}
3
  • This solution works best for me. Four parameters. Quick. Easy.
    – Oliver
    Commented Apr 20, 2015 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? jsfiddle.net/BsPsj/187
    – alexcons
    Commented Jun 23, 2017 at 18:01
  • 1
    @alexcons prepending a 0 makes it an octal integer literal. Commented Jul 2, 2017 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();
}
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.

2
  • 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? Commented Oct 12, 2012 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
    Commented Oct 14, 2012 at 7:12
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?).

1
  • 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); Commented Feb 16, 2012 at 20:18
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

1
  • 1
    the best answer for today. As native eclipse function is still experimental, it is absolutely awesome to have a fallback. thanks!
    – walv
    Commented Dec 31, 2017 at 3: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/

1
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.

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>
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);
}
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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.