“Canvas animation every Monday” – wave motion


In the previous section, we introduced the contents of trigonometric functions in canvas animation and an arrow animation that rotates with the mouse. This section mainly introduces the waveform motion of trigonometric function. include:

  1. Smooth motion

  2. Linear motion

  3. Pulse motion

1. Waveform of sin function

The waveform of sin function must be familiar to the young people. Its graph is as follows:

If you want to getsinThe value of the function between [0,2 π] can be estimated in this way in the case of discontinuity.

for(var angle=0; angle<Math.PI*2; angle+=0.1){
        console.log(Math.sin(angle)); // Print the sin value corresponding to the angle

1. Smooth movement

First introduceMath.sin(angle)First application of——Smooth motion

Smoothing refers to a smooth motion state of an object. On the contrary, it is a mechanical and simple state from 0 to 1 and then to – 1 and 0. The smooth motion is closer to the natural motion state, which is similar to the left-right swing of water plants in the water flow. There is a change in speed in the swing process.

We useMath.sinThe first motion that the function imitates is this motion similar to the swing of water and grass. In addition, becausesinThe value of the function is between [- 1,1]. So in the actual code, you need to multiply it by a larger value (that is, amplitude, you know) to make its swing look obvious. The swing of water grass is shown in the figure below,Online presentation address

The specific codes are as follows

//Aquatic plants
function Aqu(color, num, amp){
      this.startPoint = [];
      this.endPointX = [];
      this.endPointY = [];
      this.amp = [];
      this.beta = 0;
      this.color = (color == undefined)?"#3b154e":color;
      this.num = (num == undefined)?80:num;
 Aqu.prototype.init = function(){
       for(var i=0; i<this.num; i++){
           this.startPoint[i] = Math.random()*20 + i*10;
           this.endPointX[i] = this.startPoint[i];
           this.endPointY[i] = canvas.height/1.5 - Math.random()*50;
           this.amp[i] = Math.random()*10 + 40;

Aqu.prototype.draw = function(ctx){
       ctx.lineWidth = 14;
       ctx.lineCap = "round";
       ctx.globalAlpha = 0.8;
       ctx.strokeStyle =this.color;
       //Application of math.sin
       this.beta += del*0.0012;
       var l = Math.sin(this.beta);
       for(var i=0; i<this.num; i++){
          ctx.moveTo(this.startPoint[i], canvas.height);
          //Periodically change the vertex x coordinate of aquatic plants
          this.endPointX[i] = this.startPoint[i] + l*this.amp[i]
var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d');
    canvas.height = 400;
    canvas.width = 800;
    //Example aquatic plants
    var oAqu = new Aqu();
var oldTime = new Date().getTime(),
    del = null, newTime = null;
   (function drawFrmae(){
       ctx.clearRect(0, 0, canvas.width, canvas.height);
       newTime = new Date().getTime();
       del = new Date().getTime() - oldTime;
       oldTime = newTime;

Is it more fluent than mechanical addition and subtraction? Of course, you can also control the swing speed by changing the incremental angle value in math. Sin (this. Beta).

2. Linear motion

Linear motion is the simplest kind of motion. When an object moves in a certain direction at a uniform speed, it is linear motion.

The principle is very simple. Please check the specific codelinear-vertical-motion.html

       window.onload = function(){
           var canvas = document.getElementById('canvas'),
                 context = canvas.getContext('2d');
           var angle = 0,
               range = 50,
               xspeed = 1,
               yspeed = 0.05;

           var ball = new Ball();
           (function drawFrame(){

               ball.x += xspeed; // Horizontal, moving horizontally along the x-axis
               if(ball.x > canvas.width + ball.radius){
                   ball.x = -ball.radius;
               //Vertical, because the angle of the angle does not change, the ordinate remains unchanged
               ball.y = canvas.height/2+Math.sin(angle)*range;
              // angle += 0.05; // Uncomment and see what happens?

Actually, if you putangle += 0.05If you cancel the annotation, you will find that the trajectory of the ball is consistent with the image of sin function.

3. Pulse motion

In addition to the velocity acting on the object, the sin function can still act on the size change of the object. Pulse motion is the application of sin function to the change of object size.

The specific code is as follows. Please check the detailed codeplusing-motion.html

window.onload = function(){
            var canvas = document.getElementById('canvas');
            var context  = canvas.getContext('2d');

            var angle = 0,
                range = 0.5,
                speed = 0.05,
                centerScale = 1;

            var ball = new Ball();
                ball.x = canvas.width/2;
                   ball.y = canvas.height/2;

            (function drawFrame(){
                //The change of sin value leads to the change of ball.scalex and ball.scaley attributes
                ball.scaleX = ball.scaleY = centerScale + Math.sin(angle)*range;
                angle += speed;


Therefore, you should know that in addition to the position attribute, we can also combine the sin function with other attributes to form different motion forms.

Recommended Today

Java Engineer Interview Questions

The content covers: Java, mybatis, zookeeper, Dubbo, elasticsearch, memcached, redis, mysql, spring, spring boot, springcloud, rabbitmq, Kafka, Linux, etcMybatis interview questions1. What is mybatis?1. Mybatis is a semi ORM (object relational mapping) framework. It encapsulates JDBC internally. During development, you only need to pay attention to the SQL statement itself, and you don’t need to […]