JS实现烟花特效

效果展示

JS实现烟花特效

代码展示

function minbox(i,j,color) {
    
        //烟花碎片定义
    var minbox = document.createElement("div")
    minbox.style.width = '5px'
    minbox.style.height = '5px'
    minbox.style.background = color
    minbox.style.borderRadius = '50%'
    minbox.style.position = 'absolute'
    minbox.style.top = j + 'px'
    minbox.style.left = i + 'px'
    minbox.style.opacity = 1
    document.querySelector('.bg').appendChild(minbox);

    var h = Math.random()*30 - 15;
    var l = Math.random()*30 - 15;
    var o = parseInt(Math.random()*10 + 5)/100;
    var timer = setInterval(function() {
    
    
        minbox.style.left = parseInt(minbox.style.left) + l + 'px';
        minbox.style.top = parseInt(minbox.style.top) + h + 'px';
        minbox.style.opacity = minbox.style.opacity - o
        if(minbox.style.opacity <= 0) {
    
    
            clearInterval(timer);
            minbox.parentNode.removeChild(minbox)
        }
    },50)
}

function div() {
    
         //烟花上升
    var width = window.innerWidth - 30;
    var height = window.innerHeight - 30;
    var h = Math.random()*500 + 50;
    var w = Math.random()*width

    var div = document.createElement("div")
    div.style.height = '10px'
    div.style.width = '10px'
    div.style.borderRadius = '50%'
    div.style.position = 'absolute'
    div.style.top = height + 'px'
    div.style.left = w + 'px'
    div.style.background = '#ffffff'

    document.querySelector('.bg').appendChild(div);

    var timer = setInterval(function() {
    
    
        div.style.top = parseInt(div.style.top) - 30 + 'px';
        if(parseInt(div.style.top) <= h) {
    
    
            clearInterval(timer);
            div.parentNode.removeChild(div)
            show(w,h)
        }
    },50)
}
function show(w,h) {
    
        //烟花绽放
    var color = ['#fc893c','#fc3c3c','#f1ee20','#20f17e','#20c7f1','#ffffff','#d58bf7','#f78bc7','#8b9bf7']
    var index = Math.floor(Math.random() * 9 )
    
    let i = 0
    while(i<100) {
    
        //一个烟花由100个烟花碎片组成
        minbox(w,h,color[index])
        i++
    }
    
}
var state = false
function play() {
    
    
    state = !state
    // console.log(state);
    
    var width = window.innerWidth - 30;
    var height = window.innerHeight - 30;

    var timer = setInterval(function() {
    
    
        if(state) {
    
    
            div()
        }else{
    
    
            clearInterval(timer)
        }
    },500)
}

猜你喜欢

转载自blog.csdn.net/weixin_52580677/article/details/123045894