How to draw an oval in html5 canvas?
Asked Answered
L

16

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();
Lepidosiren answered 31/1, 2010 at 18:34 Comment(4)
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.Pintsize
I gave a +1, but this distorts the line along with the circle which doesn't work for me. Good info though.Buckler
@Buckler - 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... #10807730Toyatoyama
Do not put the solution in the question post. Put solutions in answer posts.Acrefoot
S
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>
Stiles answered 31/1, 2010 at 19:56 Comment(9)
This is the most general solution, as scale will distort strokes (see acdameli's answer).Orleanist
ctx.stroke() can be replace by ctx.fill() to have a filled shape.Smaragdine
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 pathBanshee
How did you derive the value for kappa?Marasmus
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/kappaStiles
Sorry about the stupid question but, what is the x and y parameters? Is it the center of the ellipse?Desmonddesmoulins
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}Stiles
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! https://mcmap.net/q/237434/-how-to-draw-an-oval-in-html5-canvasMicah
Nice, glad to hear of ellipse canvas method. Removing closePath() and adding canvas/quadratic ellipses to the jsbin tests.Stiles
D
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();
}
Digester answered 4/12, 2011 at 2:41 Comment(4)
This is pretty elegant. Let context do the heavy lifting with scale.Goff
Note the very important restore before the stroke (otherwise the stroke width gets distorted)Cornhusk
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.Denver
@JasonS Just curious why would the stroke width get distorted if you do restore after stroke?Pompadour
M
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

Micah answered 20/4, 2014 at 16:18 Comment(3)
Yeah, the implementation of this one is slow.Parole
@Epistemex Agreed. I imagine/hope it will get faster over time.Micah
According to developer.mozilla.org/en-US/docs/Web/API/…, it is supported in Opera as well nowMonarski
D
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

Drosophila answered 9/3, 2012 at 1:56 Comment(4)
This method produces the most mathematically correct ellipse. I am wondering how it compares to the others in terms of computational cost.Inadvertent
@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.Guernica
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.3msInflate
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.Mornings
G
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.

Gasaway answered 31/1, 2010 at 19:59 Comment(0)
L
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();


}
Lollygag answered 7/10, 2012 at 19:57 Comment(3)
This solution works best for me. Four parameters. Quick. Easy.Lambertson
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/187Choiseul
@Choiseul prepending a 0 makes it an octal integer literal.Lollygag
D
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();
}
Dedededen answered 7/7, 2012 at 16:23 Comment(0)
H
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.

Headway answered 16/12, 2011 at 12:39 Comment(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?Colfin
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.Headway
Y
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?).

Yancey answered 23/3, 2011 at 0:49 Comment(1)
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);Banshee
B
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

Betthel answered 1/6, 2016 at 8:38 Comment(1)
the best answer for today. As native eclipse function is still experimental, it is absolutely awesome to have a fallback. thanks!Reconciliatory
A
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/

Accepted answered 28/3, 2011 at 3:4 Comment(1)
Note that in the method given on that page, "width" isn't actually the width of the resulting ellipse. See #5695355Orleanist
L
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.

Lindberg answered 1/3, 2013 at 16:35 Comment(0)
G
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>
Goddamned answered 26/5, 2013 at 4:13 Comment(0)
C
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/

Caphaitien answered 4/8, 2013 at 17:54 Comment(0)
I
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);
}
Immersion answered 15/3, 2013 at 2:2 Comment(0)
C
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.

Clot answered 13/9, 2016 at 5:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.