<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 烟花有什么样的属性和方法?
class Fire {
constructor(color, width, x, y, num) {
// 颜色
this.color = color;
// 实弹大小
this.width = width;
// 位置
this.x = x;
this.y = y;
// 元素
this.dom = document.createElement("div");
// 装药量
this.num = num;
// 上升高度
this.distance = 300;
// 上升速度
this.speed = 8;
}
// 爆炸方法
boom() {
// 创建this.num个烟花碎片
for (var i = 0; i < this.num; i++) {
var f1 = new Fire(this.color, this.width / 4, this.x, this.y, 0)
// 随机得到一个碎片的溅射范围
var x = Math.random() * (201) + this.x - 100
var y = 1000;
// 小碎片移动到指定位置
f1.move(x, y);
f1.render();
f1.appear();
}
}
// 消失
disappear() {
this.dom.remove();
}
// 设置样式
render() {
var cssObj = {
width: this.width + "px",
height: this.width + "px",
backgroundColor: this.color,
position: "absolute",
top: this.y - this.width / 2 + "px",
left: this.x - this.width / 2 + "px",
}
for (var i in cssObj) {
this.dom.style[i] = cssObj[i]
}
}
// 出现
appear(parentNode) {
parentNode = parentNode || document.body;
document.body.appendChild(this.dom)
}
// 往上升
up() {
console.log(this)
var _this = this;
var timer = setInterval(function () {
// this变得不正确了 我们想用的是外面函数的this 但是这里也是一个函数u也有this 我们只好给外面的this起一个新名字
_this.distance -= _this.speed;
_this.y -= _this.speed;
_this.speed -= 0.1;
_this.dom.style.top = _this.y + "px"
if (_this.distance <= 0) {
clearInterval(timer)
// 定时器停止之后 要爆炸
_this.dom.remove();
_this.boom();
}
}, 20)
}
move(x, y) {
// 备份this
var _this = this;
// 随机得到一个向上的重力距离
var rand = (Math.random() * 5 + 3) * 3;
// 重力加速度
var Gy = 1.5;
// 风力加速度
var Wx = (Math.random() * 2 - 1) * 6;
var timer = setInterval(function () {
_this.y -= rand;
rand -= Gy;
_this.x += Wx;
console.log(_this.y)
_this.dom.style.top = _this.y + "px"
_this.dom.style.left = _this.x + "px";
if (_this.y >= 2000) {
clearInterval(timer)
_this.disappear();
}
}, 20)
}
}
document.onclick = function (e) {
// 初始化
var fire = new Fire("red", 20, e.clientX, e.clientY + 300, 20)
fire.render();
console.log(fire)
// 出现
fire.appear();
// 上升
fire.up();
}
</script>
</body>
</html>