首页 文章

如何将JS中的笛卡尔坐标转换为极坐标?

提问于
浏览
4

我需要使用笛卡尔坐标中的X和Y来知道极坐标中的旋转角度 .

如何在没有大量IF语句的情况下在JS中执行此操作?我知道我可以使用
this system

但我认为这对性能有害,因为它处于动画循环中 .

1 回答

  • 6

    Javascript附带内置函数,可以执行图像中显示的内容: Math.atan2()

    Math.atan2()y, x 作为参数,并以弧度为单位返回角度 .

    例如:

    x = 3
    y = 4    
    Math.atan2(y, x) //Notice that y is first!
    
    //returns 0.785398... radians, which is 45 degrees
    

    我写了这个函数,从笛卡尔坐标转换为极坐标,返回距离和角度(以弧度表示):

    function cartesian2Polar(x, y){
        distance = Math.sqrt(x*x + y*y)
        radians = Math.atan2(y,x) //This takes y first
        polarCoor = { distance:distance, radians:radians }
        return polarCoor
    }
    

    您可以像这样使用它来获得弧度的角度:

    cartesian2Polar(5,5).radians
    

    最后,如果你需要度数,你可以将弧度转换为这样的度数

    degrees = radians * (180/Math.PI)
    

相关问题