原生JS实现烟花效果
原生JS实现烟花效果,点击页面生成烟花,向四周扩散,然后再坠落下去。(这里的烟花我是用的特殊字符爱心形状)
基础css代码
/*设置基础的css样式*/ body{background:#000;overflow:hidden;} .fire{position:absolute;width:4px;height:30px;}
js代码:
1、给页面添加点击事件,生成主体烟花
//给页面设置点击事件 document.onclick=function(eve){ vare=eve||window.event; //设置一个空数组,用来后面存放小烟花 vararr=[]; //获取鼠标点击的位置 varx=e.clientX; vary=e.clientY; //设置步长 varspeed=20; //生成大烟花,设置他的css样式,出发点在可视区页面的下方 varfire=document.createElement('div'); fire.className='fire'; fire.style.background=randomColor(); fire.style.left=x+'px'; fire.style.top=document.documentElement.clientHeight+'px'; //将大烟花追加到页面上 document.body.appendChild(fire);
2、设置定时器,让烟花向上运动,删除
//生成定时器 vart=setInterval(function(){ //判断如果大烟花的TOP值小于小于目标值,清除定时器,并且将大烟花清除 if(fire.offsetTop<=y){ clearInterval(t); document.body.removeChild(fire); //执行show(生成小烟花) show(); } //让大烟花垂直向上运动 fire.style.top=fire.offsetTop-speed+'px'; },30);
3、然后在点击的位置生成小烟花,设置样式
functionshow(){ //利用循环,生成50个小烟花,给小烟花添加css属性 for(vari=0;i<50;i++){ varsFire=document.createElement('div'); //sFire.className='small-fire'; sFire.style.left=x+'px'; sFire.style.top=y+'px'; //sFire.style.background=randomColor(); sFire.style.color=randomColor(); sFire.innerHTML='❤'; sFire.style.position='absolute'; //生成随机数 vara=Math.random()*360; sFire.sx=Math.sin(a*180/Math.PI)*20*Math.random(); sFire.sy=Math.cos(a*180/Math.PI)*20*Math.random(); //将小烟花追加到页面上 document.body.appendChild(sFire); //将生成的烟花信息都添加到数组中 arr.push(sFire); } }
4、设置定时器,让小烟花完成自由落体运动
setInterval(functionmove(){ //利用循环一直改变小烟花的位置 for(vari=0;idocument.documentElement.clientWidth||arr[i].offsetTop>document.documentElement.clientHeight){ document.body.removeChild(arr[i]); //arr.splice(i,1); } } },30) }
5、最后别忘了我们的随机数和随机颜色的封装
//范围随机数 functionrandom(max,min){ returnMath.round(Math.random()*(max-min)+min); } //随机颜色 functionrandomColor(){ return"rgb("+random(0,255)+","+random(0,255)+","+random(0,255)+")"; }
最后我们的烟花效果就实现了
今天的分享就到这里,希望大家能够喜欢。
更多JavaScript精彩特效分享给大家:
Javascript菜单特效大全
javascript仿QQ特效汇总
JavaScript时钟特效汇总
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。