【问题标题】:Javascript: Formula to get Direction from X, Y CoordinatesJavascript:从 X、Y 坐标获取方向的公式
【发布时间】:2010-10-19 10:06:30
【问题描述】:

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

【问题讨论】:

    标签: javascript css geometry trigonometry shadow


    【解决方案1】:

    方向以度为单位。

    所以

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

    如果您的计算器以弧度工作(就像任何理智的计算器一样),您可以将度数转换为弧度

    radians = degrees / 180 * pi
    

    其中 pi = 3.14159... 或 Math.PI

    反之,使用'atan'

    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
    

    【讨论】:

    • +1:很好,你提到了 atan2;这是正确的,因为只要至少有一个参数不为零(与直接 atan 不同),它就没有危险。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 2015-05-23
    • 2022-11-13
    • 1970-01-01
    • 2021-07-10
    相关资源
    最近更新 更多