根据起始坐标和预定义的角度获取 javascript 中的结束线坐标

Get ending line coordinates in javascript based on starting coordinates and predefined angle

我在每次点击时都绘制 SVG 线条时遇到问题,我需要做的是仅绘制 horizontal/vertical 线条(90 度)或 45 度。线。 我已经解决的 horizontal/vertical 问题,我被卡住的地方是绘制 45deg。行,如果我知道以下信息: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;
}

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

看到这个答案:

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)

我假设您想更改最终的 return 以检查当前的 theta 是否更接近 45 而不是 0 或 90?然后如果是这样,画一条45度线代替?

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