效果如下
一、JS文件内代码
1.Utils 类
export default class Utils{
static ce(type,style,parent){
var elem=document.createElement(type);
if(style){
for(var prop in style){
elem.style[prop]=style[prop];
}
}
if(typeof parent==="string") parent=document.querySelector(parent);
if(parent) parent.appendChild(elem);
return elem;
}}
2.MoveBall类
import Utils from "./Utils.js";
export default class MoveBall {
color;
elem;
w;
speedX;
speedY;
tw;
constructor() {
this.elem = this.creatElem();
}
creatElem() {
if (this.elem) return this.elem;
this.color = Utils.randomColor();
this.w = Utils.random(30, 60);
var div = Utils.ce(div, {
width: this.w + "px",
height: this.w + "px",
borderRadius: "50%",
backgroundColor: this.color,
position: "absolute",
});
return div;
}
appendTo(parent) {
if (typeof parent === "string") parent = document.querySelector(parent);
parent.appendChild(this.elem);
this.rect = parent.getBoundingClientRect();
}
move(x, y) {
if (x) this.x = x;
if (y) this.y = y;
this.elem.style.left = this.x + "px";
this.tw=this.elem.style.left;
this.elem.style.top = this.y + "px";
}
update() {
if (this.x + this.w > this.rect.width || this.x < 0) {
this.speedX = -this.speedX;
}
if (this.y + this.w > this.rect.height || this.y < 0) {
this.speedY = -this.speedY;
}
this.x += this.speedX;
this.y += this.speedY;
this.move();
}
dispose() {
//删除移动元素
this.elem.remove();
this.elem = null;
}
}
3.html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.con {
width: 800px;
height: 400px;
border: 1px solid #000000;
position: relative;
margin: auto;
left: 0;
right: 0;
}
</style>
</head>
<body>
<div class="con"></div>
<script type="module">
import MoveBall from "./js/MoveBall.js";
import Utils from "./js/Utils.js";
var time = 0;
var bArr=[];
init();
function init() {
animation();
}
function animation() {
requestAnimationFrame(animation);
creatBall();
update();
}
function creatBall() {
time--;
if (time > 0) return;
time=15;
if(bArr.length>30){
bArr[0].dispose();
bArr[0]=null;
bArr.shift();
}
var b = new MoveBall();
b.appendTo(".con");
b.speedX = Utils.random(2, 6);
b.speedY = Utils.random(3, 8);
b.move(Utils.random(0,700),Utils.random(0,300));
bArr.push(b);
}
function update(){
bArr.forEach(item=>{
item.update();
console.log(item.x);
})
}
</script>
</body>
</html>