Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Formula to get Direction from X, Y Coordinates

I was making a utility to quickly create CSS drop shadows, and realized that this can only be done in IE with IE filters. However, the Shadow Filter uses Direction instead of (x, y) coordinates:

filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#000000');"

How can Direction be calculated from (x, y) coordinates?

Edit: Using the responses given and more details from this link: I modified my code as follows:

function(x, y){
    var d = Math.atan2(x, y) * (180 / Math.PI);
    if(d < 0){ d = 180 - d; }
    return d;
}

If you pass in Horizontal Offset and Vertical Offset that you would use as X, Y respectively, you will get a degree from 0 to 359.

like image 920
Senica Gonzalez Avatar asked Sep 01 '26 13:09

Senica Gonzalez


1 Answers

Direction is in degrees.

So

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

If your calculator works in radians (as any sane calulator should), you can convert degrees to radians with

radians = degrees / 180 * pi

where pi = 3.14159... or Math.PI

To go the other way, use 'atan'

radians = Math.atan(y / x)

In Javascript you have a Math.atan2 function which takes y and x as parameters.

radians = Math.atan2(y, x)

radians to degrees is:

degrees = radians / pi * 180

so the result is:

direction = Math.atan2(y,  x) / Math.PI * 180
like image 168
sje397 Avatar answered Sep 04 '26 03:09

sje397



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!