代码之家  ›  专栏  ›  技术社区  ›  Senica Gonzalez

Javascript:从X,Y坐标获取方向的公式

  •  2
  • Senica Gonzalez  · 技术社区  · 14 年前

    我正在制作一个实用程序来快速创建CSS阴影,并意识到这只能在IE中使用 IE filters Shadow Filter 使用方向而不是(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之间的度数。

    1 回复  |  直到 8 年前
        1
  •  10
  •   sje397    13 年前

    方向以度为单位。

    所以

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

    如果你的计算器以弧度工作(任何理智的计算器都应该这样),你可以用

    radians = degrees / 180 * pi
    

    式中,pi=3.14159。。。或Math.PI

    要走另一条路,请使用“atan”

    radians = Math.atan(y / x)
    

    Math.atan2 以y和x为参数的函数。

    radians = Math.atan2(y, x)
    

    弧度到度是:

    degrees = radians / pi * 180
    

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