用js实现烟花效果

烟花周围散放圆形烟花,记录一下,

// OOD:
// class Fire{
// constructor(){
1.创建烟花
// this.createFire();
// }
// createFire(){
创建,设置信息
2.开始运动
// this.move()
// }
// move(){
运动
3.结束了
删除
创建小烟花
// this.smallFire()
// }
// smallFire(){
创建,设置信息
4.开始运动
// this.smallMove()
// }
// smallMove(){
运动
5.删除
// }
// }

// OOP:
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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值