2

As you can see in my screenshot i try to calculate the angle between the coordinates AB and BC, in this case the angle is obviously 90°. But how can i determine this angle with javascript code?

I try to determine the angle between AB and BC

I found this thread and tried the accepted solution, but i always get 1.57instead of 90 like i expected. I rewrote the original function because i did not understood how to pass my parameters to it.

Please excuse my bad paint and math skills.

	function find_angle(Ax,Ay,Bx,By,Cx,Cy)
	{
		var AB = Math.sqrt(Math.pow(Bx-Ax,2)	+	Math.pow(By-Ay,2));    
		var BC = Math.sqrt(Math.pow(Bx-Cx,2)	+ 	Math.pow(By-Cy,2)); 
		var AC = Math.sqrt(Math.pow(Cx-Ax,2)	+ 	Math.pow(Cy-Ay,2));
		
		return Math.acos((BC*BC+AB*AB-AC*AC)	/	(2*BC*AB));
	}
	var angle = find_angle
				(
					4 ,		//Ax
					3 ,		//Ay
					
					4 ,		//Bx
					2 ,		//By
					
					0 ,		//Cx
					2		//Cy
				)
				
	alert ( angle );

7
  • Easy if you understand vectors. Use the dot or cross product.
    – duffymo
    Commented Mar 31, 2016 at 13:34
  • Thank you for the hint, i will inform about it. I learned about vectors a few years ago in school but i already forgot everything...
    – Black
    Commented Mar 31, 2016 at 13:35
  • why do you expect 90? you mean 90°? that's exactly what you get, but in radians Commented Mar 31, 2016 at 13:36
  • 1
    computers tend to work in radians unless you tell them to convert a number to degrees.
    – Forward Ed
    Commented Mar 31, 2016 at 13:38
  • 1
    hehe, sounds like function find_gold(), treasure hunters of javascript...
    – xakepp35
    Commented Feb 27, 2018 at 16:07

2 Answers 2

8

The answer is given in radians in that thread.

1.57 radians is 90 degrees (pi/2). You can convert the answer to degrees by multiplying it with 180/pi.

A = { x: 4, y: 3 };
B = { x: 4, y: 2 };
C = { x: 0, y: 2 };

alert(find_angle(A,B,C));

function find_angle(A,B,C) {
    var AB = Math.sqrt(Math.pow(B.x-A.x,2)+ Math.pow(B.y-A.y,2));    
    var BC = Math.sqrt(Math.pow(B.x-C.x,2)+ Math.pow(B.y-C.y,2)); 
    var AC = Math.sqrt(Math.pow(C.x-A.x,2)+ Math.pow(C.y-A.y,2));
    
    return Math.acos((BC*BC+AB*AB-AC*AC) / (2*BC*AB)) * (180 / Math.PI);   
}

3

Set v = A - B and w = C - B. Then the angle between v and w is the angle between vx+i*vy and wx+i*wy is the argument of w/v (as complex numbers) which is up to positive factors

(wx+i*wy)*(vx-i*vy)=wx*vx+wy*vy+i*(wy*vx-wx*vy).

The argument of a complex number is best computed using the atan2 function, thus

angle = atan2( wy*vx-wx*vy , wx*vx+wy*vy)

As previously said, the angles used are in radians, so you have to convert to degrees if desired.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.