烟花爆炸效果(随机抛物线)
css部分
html,body{
height: 100%;
overflow: hidden;//隐藏落在屏幕外面的烟花
}
*{
margin: 0;
padding: 0;
}
.box{
position: absolute;
}
.hanabi{
position: absolute;
width: 4px;
height: 4px;
}
.lead{
position: absolute;
width: 4px;
height: 4px;
background-color: red;
left: 48px;
}
js部分
function animated(element,targetObject,speed,callback){
clearInterval(element.timer)
if(typeof speed !='number'){
speed = Number(speed)
if(isNaN(speed)){
speed = 0
}
}
element.timer = setInterval(()=>{
let flag = true
for(let key in targetObject){
let current = parseFloat(getStyle(element,key))
let step = 0
if(key=="opacity"){
step = (targetObject[key]*100-current*100)/10
element.style[key] = (current*100+step)/100
}
if(key=="zIndex"){
element.style[key] = targetObject[key]
}
if(key!="opacity" && key!="zIndex"){
step = (targetObject[key]-current)/10>0?Math.ceil((targetObject[key]-current)/10):Math.floor((targetObject[key]-current)/10)
element.style[key] = current+step+'px'
}
if(parseFloat(getStyle(element,key))!=targetObject[key]){
flag = false
}
}
if(flag){
clearInterval(element.timer)
if(typeof callback =='function'){
callback()
}
}
},speed)
}
function getStyle(element,attr){
var style = window.getComputedStyle?window.getComputedStyle(element,null):element.currentStyle
return style[attr]
}
let box = document.querySelector('.box');
window.onclick = function (e){
let box = document.createElement('div');
box.className = 'box'
document.body.append(box)
box.style.left = e.clientX+'px';
box.style.top = e.clientY+'px';
let a = document.createElement('div');
a.className = 'lead';
document.body.append(a);
a.style.left = e.clientX+'px';
a.style.top = window.innerHeight +'px';
animated(a,{'top':e.clientY},40, function (){
a.remove()
let num = Math.floor(Math.random()*20+180);
for (let i = 0; i < num; i++) {
let fire = document.createElement('div');
fire.className = 'hanabi';
box.append(fire);
let d = Math.floor(Math.random()*256);
let b = Math.floor(Math.random()*256);
let c = Math.floor(Math.random()*256);
fire.style.backgroundColor = 'rgb('+d+','+b+','+c+')'
let a = Math.round(Math.random()*360)*Math.PI/180
let v = Math.round(Math.random()*30+30)
let t = 0;
fire.timer = setInterval(function (){
t = t+0.1
let X = v*Math.cos(a)*t;
let Y = -(v*Math.sin(a)*t - (9.8*Math.pow(t,2))/2)
fire.style.left = X+'px'
fire.style.top = Y+'px'
if (Y>=(window.innerHeight-e.clientY)){
clearInterval(fire.timer)
fire.remove()
}
},10)
}
})
setTimeout(function (){
box.remove()
},4000)
}