2014-04-10 198 views
7

的計算角度我想計算攝氏鼠標移動的角度。雖然我知道你不必將鼠標移動到一條直線上,但我只是試圖根據起點和終點來計算它以創建一個很好的直角。度鼠標移動

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; 
     } 

回答

5

你的計算似乎是正確的,但問題是,Math.asin(VAL)弧度返回值。使用以下函數轉換爲度數:

Math.degrees = function(radians) 
{ 
    return radians*(180/Math.PI); 
} 

然後調用Math.degrees(Math.asin(val))並且該工作!

1

Math.asin()函數返回弧度的角度。如果乘以180/pi,則會以度爲單位獲得答案。

此外,由於你要超過90度,則應該丟棄Math.abs調用,這樣就可以有阿辛負值。

+0

啊哎呀。你能告訴我爲什麼乘以180/PI的弧度給出度數? – Growler

+0

這就是以弧度表示度數的定義。 http://en.wikipedia.org/wiki/Radian#Conversion_between_radians_and_degrees – gcochard

+0

LOL我應該看這件事。最後一件事,我注意到當我在圈子中移動時,它總是以「90」來表示度數。例如:從原點移動到右上象限可以給出0到90度的範圍。從原點移動到右下象限,我期望270-360度的範圍。我該如何解決? – Growler

2

使用ATAN2函數在全圓獲得一個角度,

radians = Math.atan2(y2-y1,x2-x1); 

此外,您可能想登錄X1,X2,Y1,Y2,在計算時間的價值,這將是最好只有一個地方跟蹤鼠標位置。目前,在更新位置(X2,Y2,T2)每10ms,但(X1,Y1,T1)每次移動鼠標時。這可能導致非常不可預知的樣本組合。