原生JS实现网页烟花动画效果——前端工程师必备技能!

来源:互联网 发布:运动减肥软件 编辑:程序博客网 时间:2024/06/05 20:02

原生js实现放烟花效果,点击鼠标,然后向四周扩散,最后自由落体效果!最简单的方法实现!

CSS代码:

[html] view plain copy
  1. *{  
  2.     padding: 0px;  
  3.     margin: 0px;  
  4.     background: #000;  
  5. }  
  6. .firworks{  
  7.     width: 6px;  
  8.     height: 6px;  
  9.     position: absolute;  
  10. }  
js:代码:
[html] view plain copy
  1. <script type="text/javascript">  
  2. //封装一个颜色随机的效果  
  3.         function randomColor(){  
  4.         var color = "rgb("  
  5.         var r = parseInt(Math.random()*256);  
  6.         var g = parseInt(Math.random()*256);  
  7.         var b = parseInt(Math.random()*256);  
  8.         color = color+r+","+g+","+b+")";  
  9.         return color;     
  10.     }  
  11. //创建一个制造烟花的构造函数,第一个参数为元素,第二参数为初始x轴位置,第三参数为y轴位置。  
  12.     function Fireworks(Div,x,y){          
  13.         Div.style.backgroundColor=randomColor();   //给烟花添加背景色  
  14.         Div.className="firworks";                   //添加一个class  
  15.         document.body.appendChild(Div);  
  16.         Div.style.left=x+"px";                      //把鼠标点击坐标给div  
  17.         Div.style.top=y+"px";  
  18.         var speedX = (parseInt(Math.random()*2) == 0 ? 1 : -1)*parseInt(Math.random()*16 + 1);  //三目运算符随机移动方向,概率50%,为1时往正方向移动,负1时往反方向移动第二个随机数随机速度快慢  
  19.         var speedY = (parseInt(Math.random()*2) == 0 ? 1 : -1)*parseInt(Math.random()*20 + 1);  
  20.         this.move=function(){  
  21.             var i = 3;  
  22.             var time1=setInterval(function(){  
  23.                 i++;  
  24.                 Div.style.left=Div.offsetLeft+speedX+"px";            
  25.                 Div.style.top=Div.offsetTop+speedY+i+"px";   //当i+speedY>0时,烟花朝下运动。  
  26.                 if(Div.offsetLeft+Div.offsetWidth>window.innerWidth|| Div.offsetLeft<2 || Div.offsetTop+Div.offsetHeight>window.innerHeight || Div.offsetTop<2 ){  
  27.                     Div.remove();       //移动出可视区域记得删除div和清除定时器  
  28.                     clearInterval(time1);  
  29.                 }  
  30.             },30);  
  31.         }         
  32.     }  
  33. document.onclick=function (e){  
  34.     var evt=e||window.event;    //兼容性处理  
  35.     for(var i=0;i<80;i++){       //随机烟花的数量  
  36.         var div=document.createElement("div");  
  37.         var b=new Fireworks(div,evt.pageX,evt.pageY);  
  38.         b.move();  
  39.     }  
  40. }  
原创粉丝点击