此函数接受 2 个元素并返回元素中间的度数。
例如,我在世界地图上使用它,使平面图像沿城市方向旋转。
function degFromTwoElements(el1,el2){
var x1,x2,y1,y2,cx1,xy1,cx2,cy2,deltaX,deltaY,dx,dy,rad,deg,shortest,number;
x1 = el1.position().left;
y1 = el1.position().top;
x2 = el2.position().left;
y2 = el2.position().top;
cx1 = x1 - (el1.width() / 2);
cy1 = y1 - (el1.height() / 2);
cx2 = x2 - (el2.width() / 2);
cy2 = y2 - (el2.height() / 2);
deltaX = cx2 - cx1;
deltaY = cy2 - cy1;
y1 = Math.sqrt((Math.abs(deltaY)*Math.abs(deltaY))+(Math.abs(deltaX)*(Math.abs(deltaX))));
x1 = 0;
dy = deltaY-y1;
dx = deltaX-x1;
rad = Math.atan2(dy, dx);
deg = rad * (360 / Math.PI);
shortest;
number = Math.abs(deg);
if ((360 - number ) < number){
shortest = 360 - number;
console.log('shorter degree: ' + shortest);
return shortest;
}
else console.log('Angle is: ' + deg);
return deg;
}