This time I will show you how to make a small ball with jsanimation, what are the notes for making a small ball animation with js, the following is a practical case, let’s take a look .
1. Moving ball
In this section, we will use p5.js to make a small ball that moves on the screen.
The idea is to use variables to record the position of the ball, and then change it in the draw() function. Since the draw() function will continue to run (frequency is FPS, default 60 frames/second), So the ball moves.
The code is as follows:
var x=0; function setup() { createCanvas(400, 400); } function draw() { background(220); //width和height是关键词,分别是Canvas的宽和高 x+=2; ellipse(x,height/2,20,20); }
2. The bouncing ball
After a period of time, the ball will move out of the screen . In order to prevent the ball from running out of the screen, we add a variable to control the speed and reverse the speed when the ball leaves the screen.
The code is as follows:
var x=0; var speed=2; function setup() { createCanvas(400, 400); } function draw() { background(220); ellipse(x,height/2,20,20); //width和height是关键词,分别是Canvas的宽和高 x+=speed; if(x>width||x<0){ speed*=-1; }
Further, we can use two variables to control the speed in the x and y directions to realize the function of the ball ejecting on the canvas.
The code is as follows:
var x=200; var y=200; var Vx=2; var Vy=3; function setup() { createCanvas(400, 400); } function draw() { background(220); ellipse(x,y,20,20);//width和height是关键词,分别是Canvas的宽和高 x+=Vx; y+=Vy; if(x>width||x<0){ Vx*=-1; } if(y>height||y<0){ Vy*=-1; } }
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Detailed explanation of implicit type conversion in JS
How to use $http service in angular
The above is the detailed content of How to make a small ball animation in js. For more information, please follow other related articles on the PHP Chinese website!