【问题标题】:Get ending line coordinates in javascript based on starting coordinates and predefined angle根据起始坐标和预定义角度在javascript中获取结束线坐标
【发布时间】:2020-01-31 14:45:44
【问题描述】:

我在每次点击时都绘制 SVG 线时遇到问题,我需要做的是仅绘制水平/垂直线 (90 度) 或 45 度。线。 我已经解决的水平/垂直问题,我卡住的地方是绘制 45 度。如果我知道以下信息,则行: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 坐标以便绘制线...

【问题讨论】:

  • 画一条水平(或垂直)线并对其应用旋转(45)变换可能吗?
  • 好主意,我将再次需要对线条的长度进行某种投影,但听起来很有希望

标签: javascript math svg coordinates angle


【解决方案1】:

看到这个答案: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度线代替吗?

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    相关资源
    最近更新 更多