JavaScript小球掉落弹起
效果图:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ef362dd87905fcb48bfce0bf0020a5de.png#pic_center)
小球对象类:
export default class Ball{
elem;
speed=1;
y=-50;
constructor(){
this.elem=this.createElem();
}
createElem(){
if(this.elem) return this.elem;
let div=document.createElement("div");
Object.assign(div.style,{
width:"50px",
height:"50px",
backgroundColor:Ball.randomColor(),
borderRadius:"50%",
position:"absolute",
top:"-50px"
});
return div;
}
static randomColor(){
var col="#";
for(var i=0;i<6;i++){
col+=Math.floor(Math.random()*16).toString(16);
}
return col;
}
appendTo(select){
if(select.constructor===String)document.querySelector(select).appendChild(this.elem);
else if(select instanceof HTMLElement) select.appendChild(this.elem);
}
setX(x){
this.elem.style.left=x+"px";
}
update(){
if(this.y>400) this.speed=-this.speed;
this.speed+=0.2;
this.y+=this.speed;
this.elem.style.top=this.y+"px";
}
}
Utils方法库使用的随机数方法:
static random(min,max){
return Math.floor(Math.random()*(max-min))+min;
}
html实例化小球对象代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<script type="module">
import Ball from "./js/Ball.js";
import Utils from "./js/Utils.js";
var ids,
arr = [],
time = 30;
init();
function init() {
createBall();
animation();
}
function createBall() {
var ball = new Ball();
ball.appendTo("body");
ball.setX(Utils.random(0, 1440));
arr.push(ball);
}
function animation() {
requestAnimationFrame(animation);
allUpdate();
intervalCreate();
}
function intervalCreate() {
time--;
if (time > 0) return;
time = Utils.random(20, 40);
for (var i = 0; i < Utils.random(1, 4); i++) {
createBall();
}
}
function allUpdate() {
for (var i = 0; i < arr.length; i++) {
arr[i].update();
}
}
</script>
</body>
</html>