Next: How to use the canvas in JavaScript to make the picture rotate itself
Now that you can make an angle to rotate the picture, it's time to automatically get the angle of rotation,
So that the picture can be rotated in the direction of the mouse, so that the character can face the direction of the mouse;
Source:
functionGetangle (px,py,mx,my) {//get the angle between the center of the person and the coordinates of the mouse, and the y-axis positive half axis varx = Math.Abs (px-MX); vary = Math.Abs (py-my); varz = math.sqrt (Math.pow (x,2) +math.pow (y,2)); varcos = y/z;varRadina = math.acos (COS);//use inverse trigonometric function to find radians varAngle = Math.floor (180/(Math.pi/radina));//convert radians to angles if(mx>px&&my>py) {//Mouse in the fourth quadrantAngle = 180-angle; } if(mx==px&&my>py) {//the mouse is in the negative direction of the Y axisAngle = 180; } if(mx>px&&my==py) {//Mouse on X-axis square upwardAngle = 90; } if(mx<px&&my>py) {//Mouse in the third quadrantAngle = 180+angle; } if(mx<px&&my==py) {//the mouse is in the negative direction of the X axisAngle = 270; } if(mx<px&&my<py) {//Mouse in the second quadrantAngle = 360-angle; } returnangle; }
Ideas:
(Fig. 1)
As shown in Figure 1 ,
I need to know the angle of ∠a.
In fact, only the trigonometric functions can be used to obtain
One of the more difficult points is: the trigonometric values are obtained, the trigonometric functions are converted into radians, and then the arc is converted to an angle:
var cos = y/z; var radina = math.acos (COS); // use inverse trigonometric function to find radians var angle = Math.floor (180/(Math.pi/radina)); // convert radians to angles
However, this is not the end, here is the mouse in the first quadrant angle, so when the mouse in the second, three or four quadrant and X, Y axis to adjust the angle:
if(mx>px&&my>py) {//Mouse in the fourth quadrantAngle = 180-angle; } if(mx==px&&my>py) {//the mouse is in the negative direction of the Y axisAngle = 180; } if(mx>px&&my==py) {//Mouse on X-axis square upwardAngle = 90; } if(mx<px&&my>py) {//Mouse in the third quadrantAngle = 180+angle; } if(mx<px&&my==py) {//the mouse is in the negative direction of the X axisAngle = 270; } if(mx<px&&my<py) {//Mouse in the second quadrantAngle = 360-angle; }
This allows you to get the current ∠a angle so that the character can rotate
How JavaScript gets the angle of clockwise rotation between two points