最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to convert cartesian coordinates to polar coordinates in JS? - Stack Overflow

programmeradmin5浏览0评论

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 ,

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

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 ,

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

Share Improve this question asked Aug 26, 2015 at 6:02 levshkatovlevshkatov 4772 gold badges6 silver badges18 bronze badges 8
  • 1 That will be a fair enough effort for anyone to brainstorm a solution until you have something to show like if you have kick off with something. So as a start up, just take a paper and recall everything you need and create a pseudo code/algorithm without any programming logic and then try to mold it into JS code. It could be dirty at first but improvements can be done later. If possible, you can dump the relevant section of code here to get a much better response. :) – Rohit416 Commented Aug 26, 2015 at 6:09
  • @Rohit416 If only I could do it. I said that I know how to do it only using if constructions. I think it's obvious and I don't write here this algorithm. I ask for any other ideas how to solve this problem, maybe math library in JS or something like that. – levshkatov Commented Aug 26, 2015 at 6:18
  • 1 Yes, Math object and its methods will definitely help. Have you look at this ? – Rohit416 Commented Aug 26, 2015 at 6:23
  • 1 @Rohit416 Thanks a lot! atan2() is definitely what I was looking for. – levshkatov Commented Aug 26, 2015 at 6:26
  • it's meaningless to optimise if statements because atan will be way more costly – user3235832 Commented Aug 26, 2015 at 9:46
 |  Show 3 more comments

1 Answer 1

Reset to default 23

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)
发布评论

评论列表(0)

  1. 暂无评论