小球碰壁(面向对象)

<!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>

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值