使用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<arr.length;i++){
//设置将每次循环的第i个小烟花的运动范围
arr[i].style.left = arr[i].offsetLeft + arr[i].sx + 'px';
arr[i].style.top = arr[i].offsetTop + arr[i].sy + 'px';
//让烟花垂直方向的位置每次都增加,实现下落效果
arr[i].sy += 1;
//判断烟花是否运动出屏幕可视区,如果是,就将它删除
if(arr[i].offsetLeft<0 || arr[i].offsetLeft > 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怎么实现一个烟花效果问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。