Senica Gonzalez
Senica Gonzalez

Reputation: 8182

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.

Upvotes: 3

Views: 8683

Answers (1)

sje397
sje397

Reputation: 41812

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

Upvotes: 12

Related Questions