Angle of calculation in degrees of mouse movement

I want to calculate the angle of the mouse in degrees. Although I know that you do not need to move the mouse in a straight line, I just tried to calculate it based on the start and end points to create a good right angle.

log("ANGLE: " + getAngle(x1, y1, x2, y2)); gives strange results:

 ANGLE: 0.24035975832980774 mouse has stopped ANGLE: 1.334887709726425 mouse has stopped ANGLE: 0.2722859857950508 mouse has stopped ANGLE: 0.3715485780567732 mouse has stopped 

the code:

  $("canvas").mousemove(function(e) { getDirection(e); if (!set) { x1 = e.pageX, //set starting mouse x y1 = e.pageY, //set starting mouse y set = true; } clearTimeout(thread); thread = setTimeout(callback.bind(this, e), 100); }); function getAngle (x1, y1, x2, y2) { var distY = Math.abs(y2-y1); //opposite var distX = Math.abs(x2-x1); //adjacent var dist = Math.sqrt((distY*distY)+(distX*distX)); //hypotenuse, //don't know if there is a built in JS function to do the square of a number var val = distY/dist; var aSine = Math.asin(val); return aSine; //return angle in degrees } function callback(e) { x2 = e.pageX; //new X y2 = e.pageY; //new Y log("ANGLE: " + getAngle(x1, y1, x2, y2)); log("mouse has stopped"); set = false; } 
+7
javascript math html geometry
source share
3 answers

Your calculations seem to be correct, but the problem is that Math.asin (val) returns values ​​in radians. Use the following function to convert to degrees:

 Math.degrees = function(radians) { return radians*(180/Math.PI); } 

And then call Math.degrees (Math.asin (val)), and that should work!

+5
source share

Use the atan2 function to get the angle in a full circle,

 radians = Math.atan2(y2-y1,x2-x1); 

In addition, you might want to record the values ​​x1, x2, y1, y2 during the calculations, it would be better to have only one place where the mouse position will be tracked. At the moment, you are updating the position (x2, y2, t2) every 10 ms, but (x1, y1, t1) every time the mouse moves. This can lead to very unpredictable combinations of patterns.

+2
source share

The Math.asin() function returns the angle in radians. If you multiply by 180/pi , you will get the answer in degrees.

Also, since you want more than 90 degrees, you should refuse to call Math.abs so that you can have a negative value for aSin.

+1
source share

All Articles