碰撞小球

碰撞小球

<!DOCTYPE html>
<html lang="en">
	<head>
    <meta charset="UTF-8">
		<title>碰撞小球</title>
		<style type="text/css">
			*{
				margin: 0;
				padding:0;
			}
			.one{
				width: 800px;
				height: 400px;
				border: 1px solid gray;
				margin: 0 auto;
				position: relative;//定义相对位置
			}
			.one>div{
				border-radius: 50%;
				position: absolute;
			}
		</style>
		<script src="jquery-1.11.1.js"></script>
		<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
	</head>
<body>
    <div class="one"></div>
    <script type="text/javascript">
        $(function(){
            //创建一个随机函数
            function randFn(min,max){
                return parseInt(Math.random()*(max-min)+min);
            }
            //创建小球的属性
            function Ball(){
                this.r=randFn(1,20);
                this.x=randFn(0,$(".one").width()-this.r*2);
                this.y=randFn(0,$(".one").height()-this.r*2);
                this.c="rgba("+randFn(0,255)+","+randFn(0,255)+","+randFn(0,255)+","+"0.5)";
                this.speedX=randFn(-10,10);
                this.speedY=randFn(-6,6);
                this.div=$("<div></div>");
            }
            //画小球
            Ball.prototype.draw=function(){
                this.div.css({
                    width:this.r*2,
                    height:this.r*2,
                    background:this.c,
                    left:this.x,
                    top:this.y
                })
                $(".one").append(this.div);
            }
            Ball.prototype.run=function (){
                if(this.speedX==0){
                    this.speedX=-4
                }
                if(this.speedY==0){
                    this.speedY=-6
                }
                if(this.x<0||this.x>800-this.r*2){
                    this.speedX *=-1
                }
                if(this.y<0||this.y>400-this.r*2){
                    this.speedY *=-1
                }
                this.x+=this.speedX;
                this.y+=this.speedY;
                this.div.css({
                    left:this.x,
                    top:this.y
                })
            }
            //创建一个数组
            var ballArr=[];
            for (var i = 0; i < 200; i++) {
                var ball=new Ball();
                ballArr.push(ball);
                ball.draw();
            };
            //定时器
            setInterval(function(){
                for (var i = 0; i < ballArr.length; i++) {
                    ballArr[i].run();
                };
            },100)
        })
    </script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值