JavaScript彩色小球随机运动的效果分享

效果如图:

以下是代码:

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
	*{
		margin: 0px;
		padding: 0px;
	}
	html,body{
		height: 100%;
		width: 100%;
		overflow: hidden; /*隐藏滚动条,消除小球碰到滚动条出现的窗口闪动*/
	}
	.content{
		width: 100%;
		height: 100%;
		position: relative;
		background: black;

	}
	.ball{
		position: absolute;
		border-radius: 50%;
	}
	</style>
</head>
<body>
	<div class="content" id="con"></div>
	<script type="text/javascript">
	//定义随机函数
	function RandomNum(num1,num2){
		return Math.floor(Math.random()*(num2-num1+1)+num1);

	}
	//构造小球函数
	function Ball(){
		this.ball=document.createElement("div");
		var randomNum=RandomNum(20,50);
		this.width=randomNum
		this.height=randomNum
		//如果元素有id名,我们可以直接使用,不用document.get....获取
		this.left=RandomNum(0,con.offsetWidth-randomNum);
		this.top=RandomNum(0,con.offsetHeight-randomNum);
		this.backgroundColor="rgba("+RandomNum(0,255)+","+RandomNum(0,255)+","+RandomNum(0,255)+","+Math.random()+")";//随机颜色
		this.tempX=this.left;
		this.tempY=this.top;
		this.speedx=RandomNum(10,20)-15.5;//后面的小数是保证随机产生的方向有正有负
		this.speedy=RandomNum(10,20)-15.5;
	}
	//画小球的方法
	Ball.prototype.draw=function(){
		this.ball.style.width=this.width+"px";
		this.ball.style.height=this.height+"px";
		this.ball.className="ball";
		this.ball.style.left=this.tempX+"px";
		this.ball.style.top=this.tempY+"px";
		this.ball.style.backgroundColor=this.backgroundColor;
		con.appendChild(this.ball);
	}
	

	//运动函数
	Ball.prototype.move=function(){

		this.tempX=this.tempX+this.speedx;	
		this.tempY=this.tempY+this.speedy;
	 // 判断临界值
	    if(this.tempX+this.width>=document.body.clientWidth||this.tempX<=0){
	        this.speedx = -this.speedx;//改变方向
	    }
	    if(this.tempY+this.height>=document.body.clientHeight||this.tempY<=0) {
	        this.speedy = -this.speedy;
	    }
		 this.draw();
	}
	//产生小球
	var balls=[];
	for(var i=0;i<100;i++){
		var ball=new Ball();
		balls.push(ball);//生成的小球对象放进数组
			
	}
	function start(){
	 	for(var i = 0;i < balls.length;i++) { 
	  	balls[i].move();
	 } 
	}
	window.οnlοad=function(){
		setInterval(start,10);//设置定时器
	}

	</script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值