使用JavaScript模拟烟花的炸裂,这里实现圆形炸裂和随机炸裂两种方式,模拟烟花炸裂的操作步骤为从下而上一个大烟花,到达鼠标的位置后大烟花消失,然后有多个移动到各个地方各种颜色的小烟花,再让其消失,实现代码如下:
两种烟花都需要再js中添加,所以body内只需要一个div:
<body>
<div id="container"></div>
</body>
需要在css中对div进行修饰,并且提前对两种方式的烟花进行修饰:
#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%;
}
因为是两种烟花,所以需要两个实例,使用ES6新增的class语法实现:
class Fire{
}
class SmallFire{
}
大烟花:
class Fire{
constructor(pos){
this.cont = document.getElementById("container");
// 因为传给了new的方法,那么constructor负责接收
// 接收之后,直接解析到this,方便在后续方法中使用
this.x = pos.x;
this.y = pos.y;
}
create(){
// 创建元素设置样式和位置
this.f = document.createElement("div");
this.f.className = "fire";
this.f.style.background = randomColor();
this.cont.appendChild(this.f);
// 位置为鼠标点击的坐标的位置
this.f.style.left = this.x + "px";
// 初始信息设置完成后,开始运动
this.fireMove();
}
fireMove(){
// 调用了运动函数,传入要运动的元素,运动的属性和目标,结束后要做的事情
move(this.f,{
top:this.y
},()=>{
// 当主体烟花运动到目标后,删除主体烟花
this.f.remove();
// 准备创建小烟花:
// 准备总个数
var randomNum = random(10,20);
// 准备小烟花炸出来的圆的半径
var r = random(100,200);
// 根据个数,重复创建小烟花实例
for(var i=0;i<randomNum;i++){
// 创建实例时,需要将:以下信息都传到小烟花的实例中
// 大框,坐标,半径,个数,当前烟花的索引
var sf = new SmallFire({
cont: