先看效果图
页面代码
<div class="app">
<div class="box" ref="box">
<img class="feiji" ref="feiji" :style="{left:feijiLeft}" :src="feijiImg">
<template v-if="zidanArr.length>0">
<span class="zidan" v-for="(item,index) in zidanArr" :key="index" :style="{left:`${item.x}px`,top:`${item.y}px`}" ></span>
</template>
<template v-if="dijiArr.length>0">
<img class="diji" v-for="(item,index) in dijiArr" :src="item.srcIcon" :style="{left:`${item.x}px`,top:`${item.y}px`}">
</template>
</div>
</div>
逻辑代码部分及依赖数据
export default {
data() {
return {
boxHeight:800,
feijiLeft:'220px',
feijiImg:require('./assets/image/feiji.png'),
dijiImg:require('./assets/image/新冠.png'),
zidanArr:[],
dijiArr:[],
jishiqi:null,
dijiJishi:null,
zidanadd:null,
dijiadd:null,
}
},
methods:{
keyDown(){
document.onkeydown=e=>{
switch (e.keyCode) {
case 65:
this.leftBtn()
break;
case 68:
this.rightBtn()
break;
default:
break;
}
}
},
leftBtn(){
let l = parseInt(this.feijiLeft)
if(l>1){
this.feijiLeft = `${l-5}px`
}
},
rightBtn(){
let l = parseInt(this.feijiLeft)
if(l<500-61){
this.feijiLeft = `${l+5}px`
}
},
getDomXY(){
let x = this.$refs.feiji.offsetLeft + 28
let y = this.$refs.feiji.offsetTop-3
let zidanobj={x,y}
this.zidanArr.push(zidanobj)
},
timsetIntval(){
this.jishiqi = setInterval(()=>{
if(this.zidanArr.length>0){
this.zidanArr.forEach((item,index)=>{
if(item.y<5){
this.zidanArr.splice(index,1)
}else{
item.y = item.y - 5
}
})
}
},20)
},
zidanBtnadd(){
this.zidanadd = setInterval(()=>{
this.getDomXY()
},500)
// this.getDomXY()
},
dijiAdd(){
this.dijiadd = setInterval(()=>{
let y = 0
let x = Math.random()*(459-1)+1
let dijiObj = {x,y,srcIcon:this.dijiImg}
this.dijiArr.push(dijiObj)
},500)
},
dijixing(){
this.dijiJishi =setInterval(()=>{
this.dijiArr.forEach((item,index)=>{
if(item.y>this.boxHeight-50){
this.dijiArr.splice(index,1)
this.closeTime()
}else{
item.y = item.y + 5
}
})
},20)
},
getDomHeight(){
this.boxHeight = this.$refs.box.offsetHeight
},
closeTime(){
clearInterval(this.jishiqi)
clearInterval(this.dijiJishi)
clearInterval(this.zidanadd)
clearInterval(this.dijiadd)
}
},
watch:{
zidanArr:{
deep:true,
handler:function(newval,oldnew){
newval.forEach((item,index)=>{
this.dijiArr.forEach((t,i)=>{
if(item.x+6>t.x&&item.x<t.x+40){
if(item.y<=t.y+40){
this.zidanArr.splice(index,1)
this.dijiArr.splice(i,1)
}
}
})
})
},
immediate:true
}
},
mounted() {
this.getDomHeight()
this.zidanBtnadd()
this.timsetIntval()
this.dijiAdd()
this.dijixing()
},
created() {
this.keyDown()
}
}
样式代码
*{
margin: 0;
padding: 0;
}
.app{
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
.box{
width: 500px;
height: 100%;
background-color: black;
position: relative;
.feiji{
width: 60px;
height: 100px;
position: absolute;
bottom: 40px;
}
.zidan{
width: 6px;
height: 14px;
border-top-right-radius: 3px;
border-top-left-radius: 3px;
background-color: #e64d0b;
position: absolute;
}
.diji{
width: 40px;
height: 40px;
position: absolute;
}
}
}