我在每次点击时绘制 SVG 线条时遇到问题,我需要做的是仅绘制水平/垂直线条 (90 度) 或 45 度。线。 我已经解决的水平/垂直问题,我被卡住的地方是绘制 45deg。行,如果我知道以下信息:startCoordX、startCoordY、endCoordX、endCoordY、 Angular (正 45 度或负 -45 度。基本上我只需要调整 endCoordinates 使它们与起始坐标形成 +-45 度 Angular 线。 到目前为止,我正在这样计算两点之间的 Angular :
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 坐标以便画线...
最佳答案
查看此答案: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 度 Angular 线代替?
如有任何疑问,或者如果我对您的目标的理解有误,请告诉我。
关于javascript - 根据起始坐标和预定义 Angular 在javascript中获取结束线坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60006072/