"A little canvas weekly animation" - trigonometric functions

The main contents of this section are:

  • Trigonometric functions Introduction

  • Resolve common trigonometric functions

  • Mouse follow the angle of rotation

See trigonometric functions, mathematical term for this kind of Pythagorean theorem is not feeling his legs trembling ah! Well, even if you already scared urine, and we can not deny knowledge of secondary school finally come into play, roll up their sleeves, open the whole! ! !

1, trigonometric functions

What is the trigonometric it? Simple definition: the so-called trigonometric functions, that is, the relationship between the angle with the side of geometrically speaking! For a more visual representation, in order to allow students to recall forgotten, here I give a schematic.

Figure above embodiment illustrating the relationship between several common trigonometric functions, and edge angle (x, y, and R), as shown in formula! Then the canvas in the relationship between the angle and the side of what is it? First, we need to know is how the canvas coordinates are defined.

As shown, different from the ordinary coordinates, the coordinates of the upper left corner Canvas entire canvas as the origin of coordinates, y-axis is positive downwards, x-axis horizontally to the right. Different axes represent the angle corresponding to differ, the difference is mainly reflected in the positive and negative angle.

The figure above the canvas coordinate with ordinary coordinate feel the same, but I want to express in the canvas clockwise direction is positive, negative counter-clockwise.

2, commonly used trigonometric functions

Earlier we introduced a simple representation of trigonometric functions and canvas coordinate system. However, in the actual development, we not only want to launch from the ratio of the length of both sides of the angle. But more concerned about how (because of the location coordinates of well defined) to launch angle by a known distance. Here we have to use inverse trigonometric functions

sin(θ)=x/R   --->  θ = arcsin(x/R)
cos(θ)=y/R   --->  θ = arccos(y/R)
tan(θ)=x/y   --->  θ = arctan(x/y)

Corresponds to a javascript, the corresponding representation as follows.

sin(θ)  --->  Math.sin( θ * Math.PI/180 )
cos(θ)  --->  Math.cos( θ * Math.PI/180 )
tan(θ)  --->  Math.tan( θ * Math.PI/180 )

θ = arcsin(x/R) ---> Math.asin(x/R)*(180/Math.PI)
θ = arccos(y/R) ---> Math.acos(y/R)*(180/Math.PI)
θ = arctan(x/y) ---> Math.atan(x/y)*(180/Math.PI)

Ok! Perhaps you've seen here, nausea and vomiting have a. However, no way this is attraction of mathematics! It should be emphasized that: the angle of the canvas representation is in radians. So you can understand  θ * Math.PI/180that the angle turn to radians, such as: 30° = 30 * π /180 = π / 6. Radians while the angled turn would naturally with 弧度值`Math.asin (X / R & lt)  乘上180 [/ Math.PI`. The relationship between the conversion, slowly think will understand!

3、Math.atan2(dy, dx)

Compared to Math.asin() and Math.cos()these two functions, Math.atan()used more in development. It can obtain two orthogonal sides by an angle corresponding to the value directly. It needs to be compared to the other two long sides of the angle obtained by calculating the value, the calculation process easier! However, a problem occurs in the function determines the back angle - the angle of the presence of two identical objects specific value can not be determined rotation angle. FIG explained in detail as follows.

Because the cycle is a function of tan (-π / 2, π / 2 ), since this feature results in the computer is unable to determine the angle of rotation of which in the end! ! ! At this time, it turned out another function, Dangdang he is Math.atan2(dy, dx)! He not only solved the problem we said above, and only need to pass horizontal and vertical coordinates can be calculated from the angle corresponding to the value! Is not it cool.

4, following the mouse to rotate

This chapter describes the theoretical knowledge has been completed. Now, to start our first demo-- rotate-to-mouse.htmlthe name suggests is to follow the mouse to rotate. First, create a file arrow.js, the file is to use canvas draw an arrow, and in order to facilitate the use of the future, it will be written as a class file! code show as below:

arrow.js文件

    function Arrow() {
        this.x = 0;  //初始位置
        this.y = 0;
        this.rotation = 0;  //初始旋转角度
        this.color = '#ffff00';

    }
    //在原型上定义draw方法
    Arrow.prototype.draw = function(context){
        context.save();
        context.translate(this.x , this.y); //将坐标移到this.x 和 this.y
        context.rotate(this.rotation); //设置旋转角度
        context.lineWidth = 5;  //设置线宽
        context.fillStyle = this.color; //设置填充色
        context.beginPath();  //路径开始
        context.moveTo(-50,-25);
        context.lineTo(0,-25);
        context.lineTo(0,-50);
        context.lineTo(50,0);
        context.lineTo(0,50);
        context.lineTo(0,25);
        context.lineTo(-50,25);
        context.closePath(); //路径闭合
        context.stroke(); //描边
        context.fill(); //填充
        context.restore();
    }

 

现在我们在rotate-to-mouse.html文件中引入它,来创建一个箭头

rotate-to-mouse.html 文件

  <canvas id='canvas' width="500" height="500" style="background:#ccc;">
      you browser not support canvas
  </canvas>

  <script src="../js/utils.js"></script> //引入我们的工具函数文件
  <script src="../js/arrow.js"></script> //引入我们的箭头函数文件
  <script>
      window.onload = function(){
        var canvas = document.getElementById('canvas');
        var context = canvas.getContext('2d');
        var centerX = canvas.width/2;
        var centerY = canvas.height/2;
        
        //传入canvas,获取鼠标在canvas上移动是的坐标
        var mouse = utils.captureMouse(canvas);
             
        //新建一个arrow对象
        var arrow = new Arrow();
             
        //将arrow的坐标设置为canvas的中心
        arrow.x = centerX;
        arrow.y = centerY;
                 
      //动画循环函数
      (function drawFrame(){
          window.requestAnimationFrame(drawFrame,canvas);
          context.clearRect(0, 0, canvas.width, canvas.height);
                  
          //获取dy,dx值
          var dx = mouse.x - arrow.x,
          dy = mouse.y - arrow.y;
                      
          //设置旋转角度
            arrow.rotation = Math.atan2(dy, dx);
                    
         //调用draw方法画出
           arrow.draw(context);

      })();
}

</script>

  

我们最终得到的结果就是一个,可以跟随鼠标旋转的箭头。

图片描述

总结

这节你应该学会了如何运用三角函数,控制物体的旋转。重点公式:

dx = mouse.x - object.x;
dy = mouse.y - object.y;
object.rotation = Math.atan2(dy,dx);

转发自:《每周一点canvas动画》——三角函数

Guess you like

Origin www.cnblogs.com/rainman/p/12146156.html