Search code examples
javascriptmathdrawingellipse

Moving A Point Along Ellipse


I have created an ellipse on my canvas and now I need to draw three lines stemming from the origin. As an example let's say the first line is 90 degrees (vertical) so the point is (0, 10). I need the other two lines to be x pixels away from the point in both directions.

I'm sure I didn't describe this well enough but basically what I am trying to do is from a point on a known ellipse, find another point x distance away that lies on the ellipse.

I have tried looking for an arc of an ellipse but nothing seems to fit what I am looking for.


Solution

  • For an ellipse:

    x = a cos(t)
    y = b sin(t)
    

    So:

    x/a= cos(t)
    t = acos(x/a)
    y = b sin(acos(x/a))
    

    Plug in your values of a, b, and x and you get y.

    See https://www.mathopenref.com/coordparamellipse.html

    Rather crudely:

    var a=120;
    var b=70;
    
    var c=document.getElementById("myCanvas");
    var cxt=c.getContext("2d");
    
    var xCentre=c.width / 2;
    var yCentre=c.height / 2;
    
    
    // draw axes
    cxt.strokeStyle='blue';
    cxt.beginPath();
    cxt.moveTo(0, yCentre);
    cxt.lineTo(xCentre*2, yCentre);
    cxt.stroke();
    
    cxt.beginPath();
    cxt.moveTo(xCentre, 0);
    cxt.lineTo(xCentre, yCentre*2);
    cxt.stroke();
    
    // draw ellipse
    cxt.strokeStyle='black';
    
    cxt.beginPath();
    
    for (var i = 0 * Math.PI; i < 2 * Math.PI; i += 0.01 ) {
        xPos = xCentre - (a * Math.cos(i));
        yPos = yCentre + (b * Math.sin(i));
    
        if (i == 0) {
            cxt.moveTo(xPos, yPos);
        } else {
            cxt.lineTo(xPos, yPos);
        }
    }
    cxt.lineWidth = 2;
    cxt.strokeStyle = "#232323";
    cxt.stroke();
    cxt.closePath();
    
    // draw lines with x=+/- 40
    var deltaX=40;
    
    var y1=b*Math.sin(Math.acos(deltaX/a));
    
    cxt.strokeStyle='red';
    cxt.beginPath();
    cxt.moveTo(xCentre+deltaX, yCentre-y1);
    cxt.lineTo(xCentre, yCentre);
    cxt.lineTo(xCentre-deltaX, yCentre-y1);
    cxt.stroke();
    <html>
    <head><title>Ellipse</title></head>
    <body>
        <canvas id="myCanvas" style="position: absolute;" width="400" height="200"></canvas>
    </body>
    </html>

    (Using https://www.scienceprimer.com/draw-oval-html5-canvas as a basis as I've never used HTML canvas before.)