[英]Calculating angle in degrees of mouse movement
我想以度為單位計算鼠標移動的角度。 雖然我知道你不必直線移動鼠標,但我只是想根據起點和終點來計算它,以創造一個漂亮的直角。
log("ANGLE: " + getAngle(x1, y1, x2, y2));
給出了奇怪的結果:
ANGLE: 0.24035975832980774
mouse has stopped
ANGLE: 1.334887709726425
mouse has stopped
ANGLE: 0.2722859857950508
mouse has stopped
ANGLE: 0.3715485780567732
mouse has stopped
碼:
$("canvas").mousemove(function(e) {
getDirection(e);
if (!set) {
x1 = e.pageX, //set starting mouse x
y1 = e.pageY, //set starting mouse y
set = true;
}
clearTimeout(thread);
thread = setTimeout(callback.bind(this, e), 100);
});
function getAngle (x1, y1, x2, y2) {
var distY = Math.abs(y2-y1); //opposite
var distX = Math.abs(x2-x1); //adjacent
var dist = Math.sqrt((distY*distY)+(distX*distX)); //hypotenuse,
//don't know if there is a built in JS function to do the square of a number
var val = distY/dist;
var aSine = Math.asin(val);
return aSine; //return angle in degrees
}
function callback(e) {
x2 = e.pageX; //new X
y2 = e.pageY; //new Y
log("ANGLE: " + getAngle(x1, y1, x2, y2));
log("mouse has stopped");
set = false;
}
您的計算似乎是正確的,但問題是Math.asin(val)
以弧度為單位返回值。 使用以下函數轉換為度數:
Math.degrees = function(radians) {
return radians*(180/Math.PI);
}
然后調用Math.degrees(Math.asin(val))
它應該工作!
使用atan2函數在整圓中獲得一個角度,
radians = Math.atan2(y2-y1,x2-x1);
此外,您可能希望在計算時記錄x1,x2,y1,y2的值,最好只有一個位置跟蹤鼠標位置。 此時,每隔10ms更新一次位置(x2,y2,t2),但每次移動鼠標時都會更新(x1,y1,t1)。 這可能導致非常不可預測的樣本組合。
Math.asin()
函數以弧度為單位返回角度。 如果你乘以180/pi
,你將得到度數的答案。
此外,由於您需要超過90度,因此您應該刪除Math.abs
調用,以便為aSin設置負值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.