uniapp使用canvas实现下雨动画代码
时间: 2023-10-25 07:10:32 浏览: 169
HTML5 canvas下雨动画代码.zip
<template>
<canvas canvas-id="rainCanvas" :style="{width: canvasWidth + 'px', height: canvasHeight + 'px'}"></canvas>
</template>
<script>
export default {
data() {
return {
canvasWidth: 0,
canvasHeight: 0,
rainDrops: []
}
},
mounted() {
this.initCanvas()
this.startRain()
},
methods: {
initCanvas() {
const query = uni.createSelectorQuery()
query.select('#rainCanvas').boundingClientRect(res => {
this.canvasWidth = res.width
this.canvasHeight = res.height
}).exec()
},
startRain() {
const ctx = uni.createCanvasContext('rainCanvas')
setInterval(() => {
ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
this.rainDrops.forEach(drop => {
drop.y += drop.speed
if (drop.y > this.canvasHeight) {
drop.y = 0 - drop.length
}
ctx.beginPath()
ctx.moveTo(drop.x, drop.y)
ctx.lineTo(drop.x + drop.width, drop.y)
ctx.strokeStyle = drop.color
ctx.stroke()
})
}, 30)
setInterval(() => {
const drop = {
x: Math.random() * this.canvasWidth,
y: Math.random() * this.canvasHeight,
width: Math.random() * 3 + 1,
length: Math.random() * 10 + 10,
speed: Math.random() * 5 + 3,
color: '#FFFFFF'
}
this.rainDrops.push(drop)
}, 100)
}
}
}
</script>
阅读全文