<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
class Ball{
constructor(r,parent){
this.createBall(r,parent);
this.speedX=0;
this.speedY=0;
}
createBall(r,parent){
if(this.ball) return this.ball;
if(!parent) parent=document.body;
if(r<=0) r=20;
this.ball=document.createElement("div");
this.ball.style.width=r*2+"px";
this.ball.style.height=r*2+"px";
this.ball.style.borderRadius=r+"px";
this.ball.style.backgroundColor="red";
this.ball.style.position="absolute";
parent.appendChild(this.ball);
return this.ball;
}
update(){
this.ball.style.left=this.ball.offsetLeft+this.speedX+"px";
this.ball.style.top=this.ball.offsetTop+this.speedY+"px";
if(this.ball.offsetLeft+this.ball.offsetWidth>300 || this.ball.offsetLeft<=0){
this.speedX=-this.speedX;
}
if(this.ball.offsetTop+this.ball.offsetHeight>300 || this.ball.offsetTop<=0){
this.speedY=-this.speedY;
}
}
}
let list=[];
init();
function init() {
for(let i=0;i<10;i++){
let ball=new Ball(randomInt(10,20));
ball.speedX=randomInt(2,8);
ball.speedY=randomInt(1,10);
list.push(ball);
}
animation();
}
function randomInt(min,max) {
return Math.floor(Math.random()*(max-min)+min);
}
function animation() {
requestAnimationFrame(animation);
for(let i=0;i<list.length;i++){
list[i].update();
}
}
</script>
</body>
</html>
小球碰壁(面向对象)
最新推荐文章于 2022-03-02 14:51:19 发布