Home > Web Front-end > JS Tutorial > body text

How to make a small ball animation in js

php中世界最好的语言
Release: 2018-03-17 09:35:31
Original
2064 people have browsed it

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); 
}
Copy after login

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; 
}
Copy after login

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; 
 } 
}
Copy after login

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:

How to convert JS data types

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template