根据起始坐标和预定义角度,在JavaScript中获取结束线坐标

3

我有一个问题,每次单击时要绘制SVG线条,我需要做的是仅绘制水平/垂直线(90度)或45度线条。水平/垂直问题我已经解决了,卡在这里的是,如果我知道以下信息:startCoordX、startCoordY、endCoordX、endCoordY、角度(正45度或负45度),我需要绘制45度线条。基本上,我只需要调整终点坐标,使它们与起始坐标形成+-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坐标,以便绘制该线条...


画一条水平(或垂直)线,然后对其应用旋转(45)变换,也许可以这样做? - Robert Longson
好的想法,我需要再次为线的长度做出某种投影,但听起来很有前途。 - Kristijan Stefanoski
1个回答

1

请查看此答案:https://dev59.com/wG025IYBdhLWcg3w4qIx#18473154

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))
  };
}

有了这个,你可以将其作为第四个参数调用,例如:

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是否比0或90更接近45?然后,如果是,则绘制45度线?
如有任何问题或者我错误地理解了您的目标,请告诉我。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接