2

When drawing ellipses curves in HTML5, Canvas there's no inbuilt function, you have to scale, or make your own, I've seen this:

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

But where does that "kappa" come from? How do you calculate it, is it an infinite number (in decimals)?

2 Answers2

2

Kappa is calculated this way:

Kappa

Source

However, it will never produce a mathematical correct ellipse. For that you can use a method like this instead:

function drawEllipse(ctx, cx, cy, rx, ry) {

    var step = 0.01,                 // resolution of ellipse
        a = step,                    // counter
        pi2 = Math.PI * 2 - step;    // end angle

    /// set start point at angle 0
    ctx.moveTo(cx + rx, cy);
    for(; a < pi2; a += step) {
        ctx.lineTo(cx + rx * Math.cos(a), cy + ry * Math.sin(a));
    }
    ctx.closePath();
}

An ellipse() method is actually a part of the specification and as Loktar points out in comments it is available in Chrome and will be in the other browsers later.

0

In differential geometry, the curvature of a curve is given by κ (kappa).

Thus, the value of kappa determines the curves of your ellipse, and .5522848 might just be a choice of the developer behind this piece of code.

According to this table (from wikipedia), a positive curvature determines an ellipse :

enter image description here

Maen
  • 10,603
  • 3
  • 45
  • 71