如何在Javascript中的SVG上找到两条直线(路径)之间的角度?

XIM*_*MRX 7 javascript math svg angle

我有两条直线,就像<path>在 SVG 画布中一样。使用 LineA(A1x, A1y) (A2x, A2y)和 LineB 的像素坐标(B1x, B1y) (B2x, B2y)如何计算这些线之间的角度。

我有以下代码适用于三个点(它适用于下图中的绿色案例)。时它不起作用(A2x, A2y) != (B1x, B1y)

即使没有连接线,我如何修改这个公式才能工作。

function find_angle(p0,p1,c) {
var p0c = Math.sqrt(Math.pow(c.x-p0.x,2)+
                    Math.pow(c.y-p0.y,2));  
var p1c = Math.sqrt(Math.pow(c.x-p1.x,2)+
                    Math.pow(c.y-p1.y,2));
var p0p1 = Math.sqrt(Math.pow(p1.x-p0.x,2)+
                     Math.pow(p1.y-p0.y,2));
var angle = Math.acos((p1c*p1c+p0c*p0c-p0p1*p0p1)/(2*p1c*p0c));
return angle * (180 / Math.PI);
}
Run Code Online (Sandbox Code Playgroud)

图片

MBo*_*MBo 13

您可以利用 Math.atan2 函数对这些线段进行方向向量的叉积和点积。注意 atan2 返回范围内的有符号角-Pi...Pi

//find vector components
var dAx = A2x - A1x;
var dAy = A2y - A1y;
var dBx = B2x - B1x;
var dBy = B2y - B1y;
var angle = Math.atan2(dAx * dBy - dAy * dBx, dAx * dBx + dAy * dBy);
if(angle < 0) {angle = angle * -1;}
var degree_angle = angle * (180 / Math.PI);
Run Code Online (Sandbox Code Playgroud)