使用JavaScript怎么实现一个烟花效果
使用JavaScript怎么实现一个烟花效果?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

为格尔木等地区用户提供了全套网页设计制作服务,及格尔木网站建设行业解决方案。主营业务为网站建设、成都网站建设、格尔木网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!
基础css代码
/* 设置基础的css样式 */
body{background: #000;overflow: hidden;}
.fire{position: absolute;width: 4px;height: 30px;}js代码:
1、给页面添加点击事件,生成主体烟花
//给页面设置点击事件
document.onclick = function(eve){
var e = eve || window.event;
//设置一个空数组,用来后面存放小烟花
var arr = [];
//获取鼠标点击的位置
var x = e.clientX;
var y = e.clientY;
//设置步长
var speed = 20;
//生成大烟花,设置他的css样式,出发点在可视区页面的下方
var fire = 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、设置定时器,让烟花向上运动,删除
//生成定时器
var t = setInterval(function(){
//判断如果大烟花的TOP值小于小于目标值,清除定时器,并且将大烟花清除
if(fire.offsetTop <= y){
clearInterval(t);
document.body.removeChild(fire);
//执行show(生成小烟花)
show();
}
//让大烟花垂直向上运动
fire.style.top = fire.offsetTop - speed +'px';
},30);3、然后在点击的位置生成小烟花,设置样式
function show(){
//利用循环,生成50个小烟花,给小烟花添加css属性
for(var i=0;i<50;i++){
var sFire = 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';
//生成随机数
var a=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(function move(){
//利用循环一直改变小烟花的位置
for(var i=0;i document.documentElement.clientWidth || arr[i].offsetTop > document.documentElement.clientHeight){
document.body.removeChild(arr[i]);
// arr.splice(i,1);
}
}
},30)
} 5、最后别忘了我们的随机数和随机颜色的封装
// 范围随机数
function random(max,min){
return Math.round(Math.random()*(max-min)+min);
}
// 随机颜色
function randomColor(){
return "rgb("+random(0,255)+","+random(0,255)+","+random(0,255)+")";
}关于使用JavaScript怎么实现一个烟花效果问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。
分享标题:使用JavaScript怎么实现一个烟花效果
转载来源:http://www.jxjierui.cn/article/pidgod.html


咨询
建站咨询
