用DIV写出样式。用来表示烟花的燃放效果。
利用js运动知识来完成这一运动效果动画。
<style>
#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%;
}
</style>
<body>
<div id="container"></div>
</body>
<script src="move.2.0.js"></script>
<script>
// 一 烟花上升的主体
class fire{
constructor(pos){
this.cont=document.getElementById("container")
this.x=pos.x;
this.y=pos.y;
}
// 创建上升烟花DIV以及设置烟花上升的样式。
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.ydmove()
}
// 烟花上升的主体的运动。
ydmove(){
move(this.f,{top:this.y},()=>{this.f.remove();
// 上升的烟花运动完了之后,创建炸开的烟花。
var randomnum=random(10,20);
for(var i=0;i<randomnum;i++){
// 将上升烟花的终点设为炸开烟花的起点。
var sf=new xiaofire({
cont:this.cont,
x:this.x,
y:this.y,
});
执行炸开烟花的样式
sf.create()
}
})
}
}
// 二.创建炸开烟花
class xiaofire{
// 拿到炸开烟花的炸开起点
constructor(obj){
this.cont = obj.cont;
this.x = obj.x;
this.y = obj.y;
}
// 创建炸开烟花DIV以及设置炸开烟花的样式
create(){
this.f = document.createElement("div");
this.f.className = "small-fire";
this.f.style.background = randomcolor();
this.cont.appendChild(this.f);
this.f.style.left = this.x + "px";
this.f.style.top = this.y + "px";
// 执行炸开烟花。
this.xiaomove();
}
// 炸开烟花的运动轨迹。
xiaomove(){
// 炸开烟花运动的轨迹是随机的。
var speedX=random(-10,10);
var speedY=random(-20,0);
// 炸开烟花运动超出范围。删除所有随机出现的炸开烟花。
this.f.t=setInterval(()=>{
if(this.f.offsetTop>this.cont.offsetHeight){
clearInterval(this.f.t);
this.f.remove();
// 炸开烟花运动的整体方向。向下方运动。所以要控制Y轴。使TOP值逐渐变大。
}else{
this.f.style.left=this.f.offsetLeft+speedX+"px";
this.f.style.top=this.f.offsetTop+speedY++ +"px";
}
},30);
}
}
var ocont=document.getElementById("container");
// 三 点击事件绑定。
ocont.onclick=function(eve){
var e=eve||window.Event;
// 获得鼠标按下的坐标。
var x=e.pageX-this.offsetLeft;
var y=e.pageY-this.offsetTop;
// 保存这个坐标,给上升烟花以及炸开烟花使用。
var f=new fire({
x:x,
y:y
});
f.create()
}
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)})`;
}
</script>