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实现小球运动撞击效果,模仿气泡屏保
- 小球随机运动
- 【javascript动画之圆形运动】环绕鼠标运动作小球(兼容ie,ff,chrome,……)
- 分享一个用原生JavaScript写的带缓动效果的图片幻灯
- 分享12个效果精美的 JavaScript 倒计时脚本
- 分享12个效果精美的 JavaScript 倒计时脚本
- JavaScript] 随机幻灯片图片效果
- Javascript 鼠标移动上去 滑块跟随效果代码分享
- 分享一个自己利用javascript中的window.setInterval()定时器实现页面背景图片变换的特效(同时淡入淡出效果)
- 分享一个自己利用javascript中的window.setInterval()定时器实现页面背景图片淡入淡出效果
- Javascript实现重力弹跳拖拽运动效果
- javascript动画之圆形运动,环绕鼠标运动作小球
- javascript正则表达式提取指定的字符 分享如何随机播放采集的优酷视频地址
- 分享2011年10月网上随机搜集的超酷超有趣的web开发和Javascript代码
- 一个JavaScript的分享到效果
- 【转帖】随机彩色验证码,点击刷新效果
- 分享2011年10月网上随机搜集的超酷超有趣的web开发和Javascript代码
- javascript随机图片效果
- 分享12个效果精美的 JavaScript 倒计时脚本