<style>
#container{
width: 80%;
height: 600px;
border: 2px solid red;
background: #000;
margin:20px auto;
cursor: pointer;
position: relative;
overflow: hidden;
}
.fire{
width: 10px;
height:10px;
position: absolute;
bottom: 0;
}
.small-fire{
width: 10px;
height:10px;
position: absolute;
border-radius: 50%;
}
</style>
</head>
<body>
<div id="container"></div>
</body>
class Fire{
constructor(cont,pos){
0.解析参数,绑定到实例身上,方便方法使用
this.cont = cont;
this.x = pos.x;
this.y = pos.y;
1.创建烟花
this.createFire()
}
createFire(){
创建,设置信息
this.ele = document.createElement("div");
this.ele.className = "fire";
this.cont.appendChild(this.ele);
this.ele.style.background = randomColor();
this.ele.style.left = this.x + "px";
2.主体开始运动
this.move()
}
move(){
var that = this;
运动
move(this.ele,{
top:this.y
},function(){
3.结束了
console.log(this);
删除
that.ele.remove();
创建小烟花
that.smallFire()
})
}
smallFire(){
创建,设置信息
随机烟花个数
var num = random(10,20);
因为要运动成圆,所以需要半径
var r = random(100,200);
for(var i=0;i<num;i++){
因为循环会立即执行,每次循环创建的小烟花,需要单独保存(或单独使用(运动和删除)),所以为了防止循环创建的元素被覆盖,使用let声明变量,触发块级作用域,保存变量,方便 将来 操作
let div = document. createElement("div");
div.className = "small-fire";
div.style.left = this.x + "px";
div.style.top = this.y + "px";
div.setAttribute("bianhao",i);
div.style.background = randomColor();
this.cont.appendChild(div);
计算运动的随机目标(圆周)
利用了三角函数
var t = {
x:Math.cos( Math.PI/180 * (360/num)*i ) * r + this.x,
y:Math.sin( Math.PI/180 * (360/num)*i ) * r + this.y
};
4.开始运动
move(div,{
left:parseInt(t.x),
top:parseInt(t.y)
},function(){
因为声明小烟花时使用的let,会触发块级作用域,每次循环执行时,move及自身的回调函数会随之开启,都出在对应的块级作用域内,所以能够拿到每个块级作用域的div,可以删除
div.remove();
})
}
}
}
异步
function random(a,b){
return Math.round(Math.random()*(a-b)+b);
}
function randomColor(){
return `rgb(${random(0,255)},${random(0,255)},${random(0,255)})`;
}
因为烟花随着点击,会出现多个,每个烟花都是独立的个体,需要使用独立的对象来表示,所以,需要在每次点击的时候创建独立的对象表示每个独立的烟花
var ocont = document.querySelector("#container");
ocont.onclick = function(eve){
var e = eve || window.event;
计算坐标
var target = {
x:e.offsetX,
y:e.offsetY
}
传给程序
new Fire(ocont,target);
}
</script>