Search code examples
javascriptmathpolar-coordinatescartesian-coordinates

How to convert cartesian coordinates to polar coordinates in JS?


I need to know angle of rotation in polar coordinates using X and Y from cartesian coordinates.

How to do it in JS without a lot of IF statements? I know that I can do it using this system,

but I think that it will be bad for performance, because it is in animation cycle.


Solution

  • Javascript comes with a built in function that does what is represented in the image: Math.atan2()

    Math.atan2() takes y, x as arguments and returns the angle in radians.

    For example:

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

    I wrote this function to convert from Cartesian Coordinates to Polar Coordinates, returning the distance and the angle (in radians):

    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
    }
    

    You can use it like this to get the angle in radians:

    cartesian2Polar(5,5).radians
    

    Lastly, if you need degrees, you can convert radians to degrees like this

    degrees = radians * (180/Math.PI)