2017-06-05 187 views
0

嗨我有下面的代碼,計算在度的角度:計算角度以度爲0和360之間的返回值

var angleDeg = Math.atan2(mouse.y - base.y, mouse.x - base.x) * 180/Math.PI; 
console.log(angleDeg); 

但此刻我得到0度和180度正之間的角度和否定的。右邊0度見圖像。但我希望返回的角度在0到360之間都是正數。頂部0度。見圖片。

enter image description here

如何更新我的功能,使這個工程?我用javascript寫這個。 所以最後我希望角度值作爲圖像中的粉紅色返回。任何幫助是極大的讚賞!!!

希望這是明確的,如果不請讓我知道,所以我可以更新我的問題。

回答

2

你需要 「旋轉」 您的mouse.x和mouse.y座標大約90°(=交換Y,X與-x,y)和添加的180°(= Math.PI)的偏移:

let base = {x: 100, y: 100}; 
 

 
document.addEventListener('mousemove', event => { 
 
    let angle = Math.PI + Math.atan2(-event.x + base.x, event.y - base.y); 
 
    console.log(angle * 180/Math.PI); 
 
});
<div style="position: absolute; top: 100px; left: 100px">x</div>

1

這是最簡單的計算,如果你讓你的價值觀和你期望什麼,而不是一個圖表。

已有 - >需要

-180 - > 270

-90 - > 0

0 - > 90

90 - > 180

180 - > 270

我們看到這可以分成兩種情況:

[-180,-90)

[-90,180]

案例1

[-180,-90) - > [270,360 )

規則很簡單+450

案例2

[-90,180] - > [0,270]

這一個只是+90

所以我們讓我們的代碼

sanitize(angle){ // expecting angle within [-180, 180] 
    if(angle < -90){ 
     return angle + 450; 
    } else { 
     return angle + 90; 
    } 
}