<script src="../js/startMove.js"></script>
<script>
class Fireworks {
//第一步:构造所需要的信息
constructor(x, y) {
//获取鼠标点击的坐标
this.x = x;
this.y = y;
//获取body的高度
this.bh = document.body.offsetHeight;
//点击上升所需要的烟花
this.upfire = document.createElement('div');
//讲创建的向上烟花给document
document.body.appendChild(this.upfire);
//烟花随机颜色
this.upfire.style.backgroundColor = 'rgb(' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ')';
//烟花的初始坐标
this.upfire.style.top = this.bh - this.upfire.offsetHeight + 'px';
this.upfire.style.left = this.x + 'px';
this.upMove();
}
//烟花向上的运动
upMove() {
//调用运动函数
startMove(this.upfire, {
left: this.x,
top: this.y,
}, () => {
//运动完清除该节点,并调用下一个事件
document.body.removeChild(this.upfire);
this.Crefires();
})
}
//生成多个div块,然后爆炸
Crefires() {
//然后生成多个烟花块,这里为50
for (let i = 0; i < 50; i++) {
this.fires = document.createElement('div');
//给创建烟花给document
document.body.appendChild(this.fires);
//烟花随机颜色
this.fires.style.backgroundColor = 'rgb(' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ')';
//烟花的初始坐标
this.fires.style.top = this.y + 'px';
this.fires.style.left = this.x + 'px';
//循环调用爆炸效果,这里最好使用传参,因为如果再下面使用this.fires是脱离循环的,只是调用了一个fires.
this.Boom(this.fires);
}
}
Boom(obj) {
//再次获取鼠标坐标
let ix = this.x;
let iy = this.y;
//设置烟花随机爆炸的速度,正负都有值,这里必须要用var,不能用this,因为this指向的是一个值,所以用变量来声明。
var speedX = parseInt((Math.random() > 0.5 ? '-' : '') + this.Range(1, 15));
var speedY = parseInt((Math.random() > 0.5 ? '-' : '') + this.Range(1, 15));
//启用定时器,添加运动效果。
obj.timer = setInterval(() => {
ix += speedX;
iy += speedY++;
if (iy > this.bh) {
document.body.removeChild(obj);
clearInterval(obj.timer)
};
obj.style.top = iy + 'px';
obj.style.left = ix + 'px';
}, 0)
}
//设置一个随即范围数,上面速度里会用到
Range(a, b) {
return Math.floor(Math.random() * (b - a) + a);
}
}
document.onmousedown = function (e) {
var evt = e || event;
var fireworks = new Fireworks(evt.clientX, evt.clientY);
}
</script>
原生JS烟花特效生成
最新推荐文章于 2023-09-05 15:34:43 发布