您的位置:首页 > Web前端 > JavaScript

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

2016-11-23 22:40 441 查看
效果如图:


以下是代码:

<!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.onload=function(){
setInterval(start,10);//设置定时器
}

</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript