javascriptjquerymathgeometryellipse

How to get the edge coordinate of an ellipse in Javascript at a specific degree?


I am trying to determine the edges of an ellipse SVG in Javascript. What i have now is the center coordinate of the ellipse, the rectangle coordinates over it, and the top/left/right/bottom edges of the ellipse, but how can i determine the A,B,C,D point coordinates of an ellipse in Javascript?

enter image description here


Solution

  • Rational parametric equation of an ellipse might help:

    var e = document.querySelector('ellipse'),
      p = document.querySelector('circle');
    
    var rx = +e.getAttribute('rx'),
      ry = +e.getAttribute('ry');
    
    var angle = 0;
    const spin = () => {
        var t = Math.tan(angle / 360 * Math.PI);
        var px = rx * (1 - t * t) / (1 + t * t),
            py = ry * 2 * t / (1 + t * t);
        p.setAttribute('cx', px);
        p.setAttribute('cy', py);
        angle = ++angle % 360;
        requestAnimationFrame(spin)
    }
    
    requestAnimationFrame(spin)
    <svg viewBox="-105 -55 210 110" height="200" width="400">
    <ellipse stroke="#000" fill="#fff" cx="0" cy="0" rx="100" ry="50"/>
    <circle fill="red" r="3"/>
    </svg>

    So for your points a, b, c, d:

    var e = document.querySelector('ellipse'),
      a = document.querySelector('#a'),
      b = document.querySelector('#b'),
      c = document.querySelector('#c'),
      d = document.querySelector('#d');
    
    var rx = +e.getAttribute('rx'),
      ry = +e.getAttribute('ry');
    
    [a, b, c, d].forEach((p, i) => {
        var t = Math.tan(i * Math.PI / 4 + Math.atan(2 * ry / rx) / 2);
        var px = rx * (1 - t * t) / (1 + t * t),
            py = ry * 2 * t / (1 + t * t);
        console.log(p.id + '(' + px + ', ' + py + ')');
        p.setAttribute('cx', px);
        p.setAttribute('cy', py);
    })
    <svg viewBox="-105 -55 210 110" height="200" width="400">
    <rect stroke="#000" fill="#fff" x="-100" y="-50" width="200" height="100"/>
    <path stroke="#000" d="M-100-50L100 50zM-100 50L100-50z"/>
    <ellipse stroke="#000" fill="none" cx="0" cy="0" rx="100" ry="50"/>
    <circle id="a" fill="red" r="3"/>
    <circle id="b" fill="red" r="3"/>
    <circle id="d" fill="red" r="3"/>
    <circle id="c" fill="red" r="3"/>
    </svg>