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

How to convert cartesian coordinates to polar coordinates in JS?

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

在没有大量IF语句的情况下,如何在JS中实现?我知道我可以使用

但我认为这对性能不利,因为它处于动画循环中。

Javascript 带有一个内置函数,可以执行图像中表示的操作:Math.atan2()

Math.atan2()y, x 作为参数,returns 以弧度表示的角度。

例如:

x = 3
y = 4    
Math.atan2(y, x) //Notice that y is first!

//returns 0.92729521... radians, which is 53.1301... 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)