<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
#container {
width: 80%;
height: 600px;
border: 1px red solid;
position: relative;
margin: 20px auto;
cursor: pointer;
background: black;
}
.fire {
background: red;
position: absolute;
bottom: 0px;
width: 6px;
height: 6px;
}
.small-fire {
width: 10px;
height: 10px;
position: absolute;
border-radius: 50%;
}
</style>
<body>
<div id="container">
</div>
<script>
let contObj = document.getElementById('container');
contObj.onclick = (eve) => {
let posObj = {
left: eve.offsetX,
top: eve.offsetY
}
new Fire(contObj, posObj)
}
function Fire(contObj, posObj) {
this.contObj = contObj;
this.posObj = posObj;
let bigFire = document.createElement('div');
bigFire.className = 'fire';
bigFire.style.background = this.getColor();
bigFire.style.left = this.posObj.left + 'px';
this.contObj.appendChild(bigFire)
this.move(bigFire, {
top: this.posObj.top }, function () {
bigFire.remove();
this.smallFire();
}.bind(this))
}
Fire.prototype.smallFire = function () {
for (let i = 0; i < 20; i++) {
let smallDiv = document.createElement('div');
smallDiv.className = 'small-fire'
smallDiv.style.background = this.getColor();
smallDiv.style.left = this.posObj.left + 'px';
smallDiv.style.top = this.posObj.top + 'px'
let endTop = this.random(0, this.contObj.offsetHeight - smallDiv.offsetHeight)
let endLeft = this.random(0, this.contObj.offsetWidth - smallDiv.offsetWidth);
this.contObj.appendChild(smallDiv);
let that = this;
that.move(smallDiv, {
left: endLeft, top: endTop }, function () {
console.log(6666);
smallDiv.remove();
})
}
}
Fire.prototype.move = function (ele, targetObj, cb) {
let onOff = false;
var times = setInterval(() => {
for (let attr in targetObj) {
let tmpPos = parseInt(this.getPos(ele, attr));
let speed = (targetObj[attr] - tmpPos) / 10;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (tmpPos + speed == targetObj[attr]) {
onOff = true;
}
ele.style[attr] = tmpPos + speed + 'px';
}
if (onOff) {
clearInterval(times);
cb && cb();
}
}, 30)
}
Fire.prototype.getPos = function (obj, attr) {
if (obj.currentStyle) {
return obj.currentStyle[attr];
} else {
return getComputedStyle(obj)[attr]
}
}
Fire.prototype.random = function (min, max) {
return Math.round(Math.random() * (max - min) + min);
}
Fire.prototype.getColor = function () {
let c = '#';
for (var i = 0; i < 6; i++) {
c += this.random(0, 16).toString(16)
}
return c;
}
</script>
</body>
</html>
如果设置圆周运动改变小烟花的left top的 目标值
// 设置起始位置,鼠标点击的位置
smallDiv.style.left = this.posObj.left + 'px';
smallDiv.style.top = this.posObj.top + 'px'
// 随机终点
var endTop = parseInt(Math.sin(Math.PI / 180 * 360 / fireNum * i) * r) + this.posObj.top;
var endLeft = parseInt(Math.cos(Math.PI / 180 * 360 / fireNum * i) * r) + this.posObj.left