views:

284

answers:

5

In javascript, I am trying to draw a line that is at an angle that is user defined.

Basically, I have a point (x,y) and an angle to create the next point at. The length of the line need to be 10px.

Let's say that the point to start with is (180, 200)... if I give it angle "A" and the (I guess)hypotenuse is 10, what would my equation(s) be to get the X and Y for a slope?

Thanks for your help!

A: 

Don't be lazy - learn the very simple formulae for trigonometry.

And just so this isn't a flame (:)), you can use the Math.sin, Math.cos and Math.tan functions to do your dirty work.

Andrzej Doyle
+5  A: 

well, from basic trigonometry...

sin A° = Y/10

cos A° = X/10

10^2 = Y^2 + X^2

flesh
Alternatively, cosA = X / 10 to solve for X. Upvoted for the only person to actually provide an answer so far.
Ron Warholic
cheers sid - and hat tip for cos:)
flesh
Indeed; sometimes people forget this is a question and answer site and not a forum.
Ron Warholic
+3  A: 

As Mr Doyle snarkily implied, the math isn't that hard, but :

1) Make sure you are clear about what the angle is referenced to, and what directions your coordinates go; most simple trig stuff assumes you are dealing with traditional cartesian coordinates with x increasing to the right, and y increasing up the page, whereas most drawing api have y increasing down the page and x increasing to the right.

2) make sure you understand whether the math functions need degrees or radians and supply them with the appropriate arguments.

Mikeb
Yes. There's not enough information given. Coordinate system an information about where the 0 angle points and which direction it goes are needed.
Nosredna
+1  A: 

Assuming H = Hypotenuse (10 in your example), this is the formula for your slope:

Y2 = H(Sin(A)) + Y1
   = 10(Sin(A)) + 200

X2 = Sqrt((H^2)-(Y2^2)) + X1
   = Sqrt(100 - (Y2^2)) + 180

So now you've got

(180, 200) -> (X2, Y2)

Where X2, Y2 will vary depending on the values of A and H

To check our calculation - A (as entered by the user) can be calculated using the slope equation replacing the X1, X2, Y1 and Y2 values with the original input and resulting output.

A = InvTan((Y2 - Y1) / (X2 - X1))
  = InvTan((Y2 - 200) / (X2 - 180))
BenAlabaster
+1  A: 

Maybe a better way to look at the problem is using vectors:

alt text

You can also write the vector this way:

alt text

where

alt text

Setting the first equal to the second lets us solve for the end point given the starting point, the angle, and the distance:

alt text

alt text

duffymo