2010-10-19 132 views
2

我正在製作一個實用程序來快速創建CSS陰影,並意識到只能在IE中使用IE filters。然而,Shadow Filter使用方向,而不是(X,Y)座標:Javascript:從X,Y座標獲得方向的公式

filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#000000');" 

怎樣的方向從計算出(X,Y)座標?

編輯:使用從this link給出的答覆和更多的細節:我修改我的代碼如下:

function(x, y){ 
    var d = Math.atan2(x, y) * (180/Math.PI); 
    if(d < 0){ d = 180 - d; } 
    return d; 
} 

如果您在水平通過偏移和垂直偏移,你會爲X,Y分別使用,您將獲得0至359的學位。

回答

11

方向以度爲單位。

所以

x = cos(direction) 
y = sin(direction) 

如果您的計算器弧度的作品(如任何理智的calulator應該),你可以轉換爲弧度與

radians = degrees/180 * pi 

其中pi = 3.14159 ...或者數學。 PI

走另外一條路,用 '反正切'

radians = Math.atan(y/x) 

在Javascript中,您有一個Math.atan2函數,它需要y和x作爲參數。

radians = Math.atan2(y, x) 

弧度到度是:

degrees = radians/pi * 180 

所以結果是:

direction = Math.atan2(y, x)/Math.PI * 180 
+0

+1:好的,你提到ATAN2;這是正確的,因爲只要其中至少有一個參數不是零(與直接的atan不同),它就是無危害的。 – 2010-10-19 10:21:57

+0

謝謝。很好的解釋。 – 2010-10-19 10:26:31