【问题标题】:How to get the edge coordinate of an ellipse in Javascript at a specific degree?如何在特定程度上获取Javascript中椭圆的边缘坐标?
【发布时间】:2018-08-02 18:58:02
【问题描述】:

我正在尝试在 Javascript 中确定椭圆 SVG 的边缘。我现在拥有的是椭圆的中心坐标、其上的矩形坐标以及椭圆的上/左/右/下边缘,但是我如何确定椭圆的 A、B、C、D 点坐标在Javascript中?

【问题讨论】:

  • 希望这是 2D ... 如果您的意思是对角线的特定度数,则使用带有 45,135,225,315 度数的参数椭圆方程。如果你真的是指任何角度,那么计算与更大的半轴对齐的坐标,并从椭圆方程计算另一个。

标签: javascript jquery math geometry ellipse


【解决方案1】:

Rational parametric equation 的椭圆可能会有所帮助:

var e = document.querySelector('ellipse'),
  p = document.querySelector('circle');

var rx = +e.getAttribute('rx'),
  ry = +e.getAttribute('ry');

var angle = 0;
const spin = () => {
    angle *= angle !== 360;
    var t = Math.tan(angle++ / 360 * Math.PI);
    var px = rx * (1 - t ** 2) / (1 + t ** 2),
        py = ry * 2 * t / (1 + t ** 2);
    p.setAttribute('cx', px);
    p.setAttribute('cy', py);
    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>

所以对于你的点 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 ** 2) / (1 + t ** 2),
        py = ry * 2 * t / (1 + t ** 2);
    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>

【讨论】:

    【解决方案2】:

    例如,让我们计算坐标为A.x, A.y 的点A。为此,我们首先假设椭圆的中心O 的坐标为0, 0。为了得到最后的一般情况,最终结果将仅移动O.x, O.y

    现在,连接点OR2 的线描述为

    y = (R2.y / R2.x) * x
    

    为了简化下面的符号,我们用a := R2.y / R2.x 表示。椭圆本身被定义为一组满足:

    (y/yd)**2 + (x/xd)**2 = 1
    

    所以为了得到交集,我们可以将第一个方程代入第二个方程。这产生:

    x**2 * ( (a/yd)**2 + 1/xd**2 ) = 1
    

    因此(由于交点在第一象限,我们知道x有一个正号):

    x = 1 / Math.sqrt( (a/yd)**2 + 1/xd**2 )
    y = a * x
    

    最后,要解决椭圆中心的非零偏移量,我们只需添加相应的偏移量即可。因此:

    x = O.x + 1 / Math.sqrt( (a/yd)**2 + 1/xd**2 )
    y = O.y + a * x
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      相关资源
      最近更新 更多