一、style
` #container{
width: 80%;
height: 600px;
border: 2px solid red;
background: #000;
margin:20px auto;
position: relative;
overflow: hidden;
}
.fire{
width: 10px;
height:10px;
position: absolute;
bottom: 0;
}
.small-fire{
width: 10px;
height:10px;
position: absolute;
border-radius: 50%;
} `
二、body
<div id="container"></div>
三、JS
<script src = "../move.js"></script>
<script>
function Fire(ops){
this.x = ops.x;
this.y = ops.y;
this.cont = ops.cont;
this.create();
}
Fire.prototype.create = function(){
this.div = document.createElement("div");
this.div.className = "fire";
this.cont.appendChild(this.div);
this.div.style.background = randomColor();
this.div.style.left = this.x +"px"
this.firemove();
}
Fire.prototype.firemove = function(){
move(this.div,{top:this.y},()=>{
this.div.remove();
var r = random(100,200);
var num = random(10,20);
for(var i=0;i<num;i++){
new SmallFire({
x:this.x,
y:this.y,
cont:this.cont,
r,num,i
});
}
})
}
function SmallFire(ops){
this.x = ops.x;
this.y = ops.y;
this.cont = ops.cont;
this.r = ops.r;
this.num = ops.num;
this.i = ops.i;
this.create();
}
SmallFire.prototype.create = function(){
this.div = document.createElement("div");
this.div.className = "small-fire";
this.cont.appendChild(this.div);
this.div.style.background = randomColor();
this.div.style.left = this.x +"px";
this.div.style.top = this.y + "px";
this.fireMove();
}
SmallFire.prototype.fireMove = function(){
var reg = (360/this.num)*(this.i);
var target = {
x:parseInt(Math.cos(reg/(180/Math.PI))*this.r+this.x),
y:parseInt(Math.sin(reg/(180/Math.PI))*this.r+this.y),
}
move(this.div,{left:target.x,top:target.y},function(){
this.div.remove();
}.bind(this))
}
var ocont = document.getElementById("container");
ocont.onclick = function(eve){
var e = eve || window.event;
new Fire({
x:e.offsetX,
y:e.offsetY,
cont:this
});
}
//随机数功能
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)})`
}
//角度转弧度,公式
//jiao = 180 / pai * hu
四、封装的功能函数move
function move(ele, data, cb){
clearInterval(ele.t);
ele.t = setInterval(() => {
var flag = true;
for(var i in data){
var now = i === "opacity" ? getStyle(ele, i) * 100 : parseInt(getStyle(ele, i));
var speed = (data[i] - now)/10;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
ele.style[i] = i === "opacity" ? (now + speed)/100 : now + speed + "px";
if(now !== data[i]){
flag = false;
}
}
if(flag){
clearInterval(ele.t);
cb && cb();
}
}, 30);
}
function getStyle(ele, attr){
if(ele.currentStyle){
return ele.currentStyle[attr];
}else{
return getComputedStyle(ele,false)[attr];
}
}
![烟花效果](https://i-blog.csdnimg.cn/blog_migrate/97e57b2b8b250b9382c2645056dc0d9d.png#pic_center)