温馨提示:本文翻译自stackoverflow.com,查看原文请点击:math - Get ending line coordinates in javascript based on starting coordinates and predefined angle
coordinates javascript math svg angle

math - 根据起点坐标和预定义角度在JavaScript中获取终点线坐标

发布于 2020-04-05 00:28:52

我在每次单击时都绘制SVG线时遇到一个问题,我需要做的是仅绘制水平/垂直线(90度)或45度。线。我已经解决的水平/垂直问题是绘制45度。如果我知道以下信息,则输入line:startCoordX,startCoordY,endCoordX,endCoordY,角度(正45度或负-45度。基本上,我只需要调整endCoordinates以使其与起始坐标形成+ -45度角线。到目前为止,我正在像这样计算两点之间的角度:

angle(startx, starty, endx, endy) {
        var dy = endy - starty;
        var dx = endx - startx;
        var theta = Math.atan2(dy, dx); // range (-PI, PI]
        theta *= 180 / Math.PI; // rads to degs, range (-180, 180]
        //if (theta < 0) theta = 360 + theta; // range [0, 360)
        return Math.abs(theta) > 90 ? theta % 90 : theta;
}

有什么想法可以实现吗?我需要另一个函数来返回我的X和Y结束坐标以画线...

查看更多

提问者
Kristijan Stefanoski
被浏览
117
Alex L 2020-02-03 16:31

看到这个答案:https : //stackoverflow.com/a/18473154/9792594

function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
  var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;

  return {
    x: centerX + (radius * Math.cos(angleInRadians)),
    y: centerY + (radius * Math.sin(angleInRadians))
  };
}

这样,您可以使用45作为第四个参数来调用它,即:

const pos = polarToCartesian(startx, starty, radius, 45)

这要求您知道要绘制的半径。或者您可以从函数中获取它,例如:

angle(startx, starty, endx, endy) {
        const dy = endy - starty;
        const dx = endx - startx;
        const radius = Math.sqrt(dy**2 + dx**2);
        const pos = polarToCartesian(startx, starty, radius, 45);
        let theta = Math.atan2(dy, dx); // range (-PI, PI]
        theta *= 180 / Math.PI; // rads to degs, range (-180, 180]
        //if (theta < 0) theta = 360 + theta; // range [0, 360)
        return Math.abs(theta) > 90 ? theta % 90 : theta;
}

重要行const radius = Math.sqrt(dy**2 + dx**2);之后是const pos = polarToCartesian(startx, starty, radius, 45)

我假设您想更改最终收益以检查当前theta是否更接近45,而不是0或90?然后,如果是,则绘制45度线?

有任何疑问,或者如果我对您的目标有不正确的理解,请告诉我。