0

I found a helpful function to draw an ellipse with any width and height. Is there a way to make it appear rotated in 3D by sending it pitch, yaw and roll values?

function drawEllipse(ctx, x, y, w, h, pitch, yaw, roll, strokeColor) {
    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.strokeStyle = strokeColor
    ctx.moveTo(x, ym);

    // draw 4 quarters of the elipse
    // top left, top right, bottom right, bottom left
    /*
    cp1x
    The x-axis coordinate of the first control point.
    cp1y
    The y-axis coordinate of the first control point.
    cp2x
    The x-axis coordinate of the second control point.
    cp2y
    The y-axis coordinate of the second control point.
    x
    The x-axis coordinate of the end point.
    y
    The y-axis coordinate of the end point.
    */
    ctx.bezierCurveTo(x,       ym - oy, xm - ox, y,       xm, y);  // quarter 1
    ctx.bezierCurveTo(xm + ox, y,       xe,      ym - oy, xe, ym); // quarter 2
    ctx.bezierCurveTo(xe,      ym + oy, xm + ox, ye,      xm, ye); // quarter 3
    ctx.bezierCurveTo(xm - ox, ye,      x,       ym + oy, x,  ym); // quarter 4

    ctx.stroke();
}
Chewie The Chorkie
  • 4,896
  • 9
  • 46
  • 90
  • ...why would you use bezier curves when the Canvas API has [ellipse()](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/ellipse) available _as standard function_? With that said, do you actually want to draw 3D (e.g, webgl) or are you asking about to fake it using projection? – Mike 'Pomax' Kamermans Oct 11 '19 at 04:46
  • I had no idea there was an ellipse function available, so thanks for that. It doesn't seem though that ellipse could warp itself to show a side further or nearer to an observer. WebGL is too heavy an unnecessary for what I want to achieve. I want to "fake" it, yes. – Chewie The Chorkie Oct 11 '19 at 16:11
  • 1
    Nothing heavy about webgl, for simple stuff like this, it's simple, with a million tutorials on the web that basically cover this in about as many lines as your post's code snippet is. If you want projections, then what you probably want is to build it using `beginShape`, `vertex`, and `endShape` instead, using the extremely simple formula for computing points on an ellipse given an input angle, and instead of straight up calling `ctx.vertex(x,y)`, call `ctx.vertex(...project(x,y))`. While that moves the problem to implementing projection, there are a fair number of answers on SO already. – Mike 'Pomax' Kamermans Oct 11 '19 at 17:16
  • Thank you, maybe I'll use that instead. I didn't know it had support for all browsers. – Chewie The Chorkie Oct 11 '19 at 18:33

0 Answers0