# Weekly point canvas animation – speed and acceleration (2)

Time：2021-9-3

In the previous section, we introduced the basic concepts of speed, including`Velocity along the axis`, and more pervasive`Velocity in any direction`, at the end of the article, we made an example`Mouse follow`And by changing the shape of the object`rotation`Property makes an extension on speed. Through the study in the previous section, you will find that our objects can move in any direction, but this is not enough, because our objects are doing`Uniform motion`
Since there are`Uniform motion`Yes, of course`Variable speed motion`Hello! In this section, we introduce another important content of this chapter`acceleration`。 This section will be divided into the following parts:

• Basic concept of acceleration

• Acceleration along the coordinate axis

• Synthesis and decomposition of acceleration

• Gravitational acceleration

• Spacecraft (application example)

• Summary of this chapter

## 1. Basic concept of acceleration

In case some students return all their physics knowledge to the teacher! I’ll introduce what acceleration is first, okay! In a word, the acceleration isA physical quantity describing the speed of an object。 We know that speed is a physical quantity that represents the speed of an object’s motion, and here acceleration is used to represent the change of speed. With physical`Time / speed`This is shown in the figure: From the figure, we can see that the speed of uniform motion remains unchanged, while the speed of variable speed motion changes with time. As shown in the figure, a uniformly accelerated motion is shown here Δ In the time of T, the speed increases Δ v. So`acceleration`It can be expressed as`a= Δv / Δt`。 ok！ Stop the disgusting physics formula! Let’s take a look at how it is implemented in the code.

## 2. Acceleration along the coordinate axis

Here, we first introduce the acceleration along the coordinate axis. The specific code is as follows:

``````<canvas id="canvas" width="500" height="500" style="background:#000;">
</canvas>
< script > < / script > // import tool function file
< script > < / script > // introduce balls
<script>
var canvas = document.****getElementById("canvas");
var context = canvas.getContext("2d");

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

var vx = 0, ax = 0.1; // Define the initial velocity VX and the acceleration a
(function drawFrame(){
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0,0,canvas.width,canvas.height);

vx += ax; // Velocity is added to the value of acceleration for each frame
ball.x += vx;
ball.draw(context);
}());
}
</script>``````

In the above code, we first define the speed and acceleration, and then add the acceleration to each frame of the speed in the animation cycle, so that the value of the speed in each frame is increasing, and the position of the ball will increase more and more in each frame, which is reflected in the animation. Here I would like to thank enthusiastic netizens for recommending GIF production tools to me, so that this article is no longer dry words and pictures. No more nonsense, above:

Uniform motion Accelerated motion In order to make the effect more prominent, the picture of uniform motion is put here, which is compared with the picture of accelerated motion. In the sample code, the ball moves along the X axis, of course, you can also move along the Y axis, or both. When you define the acceleration on the x-axis and y-axis at the same time, you will find that, like the velocity in any direction, the ball will move in the direction of the combined velocity of the two, which leads to our next part – acceleration in any direction.

## 3. Synthesis and decomposition of acceleration

With the foreshadowing of the synthesis and decomposition of velocity in the previous section, it becomes very simple here. Acceleration can also be synthesized and decomposed like velocity. Here, we assume that the small ball should be accelerated with an acceleration of 0.05 along the direction of 30 degrees. The specific code is as follows:

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

var ball = new Ball(20);
ball.x = 0;
ball.y = 0;

Var VX = 0, vy = 0, // initial speed is 0
Ax = 0, ay = 0, // sub acceleration is 0
Angle = 30, // direction of motion
aTotal = 0.05; //  Defines the magnitude of the acceleration

(function drawFrame(){
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0,0,canvas.width,canvas.height);

//Acceleration decomposition
ax = Math.cos(30 * Math.PI/180)*aTotal;
ay = Math.sin(30 * Math.PI/180)*aTotal;

vx += ax;
vy += ay;

ball.x += vx;
ball.y += vy;
ball.draw(context);
}());
}``````

The specific effect is shown in the figure below: Like the concept of velocity in any direction, we set the magnitude of acceleration and the direction of object motion. Then, in the animation cycle, decompose the acceleration into horizontal and vertical directions, and then add the corresponding acceleration values to the horizontal and vertical speeds in each frame, so that we can get a small ball that accelerates (decelerates) in any direction.

## 4. Gravity acceleration

In this part, we introduce a special acceleration – gravitational acceleration. Gravitational acceleration is actually formed by the gravity between two objects. Later, we will have a chapter to introduce universal gravity and apply it to our animation.

For this special acceleration, I believe you should not feel strange to it, because in the middle school textbooks`G`I don’t know how many times this symbol appears. What we need to know is that on earth, any object falling from the air to the ground has a vertical downward acceleration.

ok！ Code time, our topic is:`The ball falls freely from the air to the ground, then bounces up and goes back and forth until its final speed is zero and stays on the ground`。 ok This time, let’s take a look at the simulated effect: The specific codes are as follows:

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

var ball = new Ball(20, "red");
ball.x = canvas.width/2
ball.y = canvas.height/2 - 200;

Var vy = 0, // initial speed
Gravity = 0.2, // define gravity acceleration
bounce = -0.8; // Define bounce factor

//Collision detection
function checkGround(ball){
vy *= bounce; // The speed reverses and decreases
}
}

(function drawFramw(){
window.requestAnimationFrame(drawFramw, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);

vy += gravity;
ball.y += vy;

//Collision detection
checkGround(ball);
ball.draw(context);
}());
}``````

In this code, in addition to the contents introduced in this chapter, there are also some contents introduced in the next chapter, but with your intelligence, I believe it is a piece of cake, right! In the initialization phase, we define the initial velocity in the y-axis direction`vy`And gravitational acceleration`gravity`And a rebound coefficient`bounce`。 Here we do a simple collision detection. When the small ball falls to the ground (that is, the bottom of the canvas canvas), its position is`canvas.height - ball.radius`And the speed rebounds and the direction is upward. Then the animation function is called to call the collision detection function, so that the effect of landing rebound is achieved, and what is the reason why it will stay on the ground at last?`bounce`It’s a decimal. Every collision`vy`Will decrease. Well, it’s just a simple animation, so I won’t bother talking.

## 5. Spacecraft

In this example, we want to achieve the following results:The direction keys on the keyboard control the spacecraft to move in different directions。 Here we need to create a new one`spaceShip.js`Class file. It is worth noting that with this file, your JS folder should contain the following four files:

• utils.js

• arrow.js

• ball.js

• ship.js

The code of ship.js file is as follows:

``````Spaceship.js file

function SpaceShip(){
this.x = 0;
this.y = 0;
this.width = 25;
this.height = 25;
this.rotation = 0;
this.showFlame = false;
}

SpaceShip.prototype.draw = function(context){
context.save();
context.beginPath();
context.translate(this.x, this.y);
context.rotate(this.rotation);
context.strokeStyle = "#ffffff";
context.moveTo(10, 0);
context.lineTo(-10, 10);
context.lineTo(-5, 0);
context.lineTo(-10, -10);
context.lineTo(10, 0);
context.closePath();
context.stroke();
if(this.showFlame == true){
context.save()
context.beginPath();
context.strokeStyle = "#f69";
context.moveTo(-7.5, -5);
context.lineTo(-15, 0);
context.lineTo(-7.5, 5);
context.stroke();
context.restore();
}
context.restore();
}``````

The renderings are as follows: The specific codes are as follows:

``````<canvas id="canvas" width="1000" height="500" style="background:#000;">
</canvas>
<script></script>
<script></script>
<script>
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d');

var spaceShip = new SpaceShip();
spaceShip.x = canvas.width/2;
spaceShip.y = canvas.height/2;

//Initialization
var vr = 0,
vx = 0,
vy = 0,
ax = 0,
ay = 0,
angle = 0,
thrust = 0;

//Control the value of each variable through the direction key
switch (event.keyCode){
case 37:    //left
vr = -3;
vx = 0;
vy = 0;
break;
case 39:  //right
vr = 3;
vx = 0;
vy = 0;
break;
case 38: //up
spaceShip.showFlame = true;
thrust = 0.05;
break;
case 40:
ax = 0;
ay = 0;
vx = 0;
vy = 0;
break;
}
}, false);

vr = 0;
thrust = 0;
spaceShip.showFlame = false;
}, false);

(function drawFrame(){
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);

//Angle
spaceShip.rotation += vr *Math.PI/180;

angle = spaceShip.rotation;
ax = Math.cos(angle)*thrust;
ay = Math.sin(angle)*thrust;

vx += ax;
vy += ay;

spaceShip.x += vx;
spaceShip.y += vy;

spaceShip.draw(context);

}());
}``````

OK, let’s see if it’s cool. Now you can control the spacecraft to move in any direction as long as you use the direction key on the keyboard. Put the code in your editor and experience it yourself. Although our spaceship is only a simple polygon, it can spit fire! ha-ha!

## 6. Summary

Formula summary in this chapter:

``````//Velocity in any direction
vx = speed * Math.cos(angle);
vy = speed * Math.sin(angle);

//Acceleration in any direction
ax = force * Math.cos(angle);
ay = force * Math.xin(angle);

//Change speed
vx += ax;
vx += ay;

//Change position
object.x += vx;
object.y += vy;``````

ok Come here`Velocity and acceleration`The chapter comes to an end. We explain the basic concepts of velocity and acceleration, and realize many different effects combined with the previous trigonometric functions. Can a simple example arouse your infinite creativity? Look forward to the next chapter – boundary and friction

## 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 […]