代码
<template>
<canvas id="background"></canvas>
</template>
<script lang="ts" setup>
import { onMounted } from 'vue'
type dot = {
x: number
y: number
xa: number
ya: number
color: string
radius: number
}
function getRandomNumber(min: number, max: number) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
function getRandomColor() {
let a = Math.random() * 0.8 + 0.1
let r = 255
let color = `rgba(${r}, ${r}, ${r}55, ${a})`
return color
}
onMounted(() => {
let canvas = document.getElementById('background') as HTMLCanvasElement
let ctx = canvas.getContext('2d') as CanvasRenderingContext2D
canvas.width = canvas.clientWidth
canvas.height = canvas.clientHeight
const dots: dot[] = []
for (let i = 0; i < 500; i++) {
let x = Math.random() * canvas.width
let y = Math.random() * canvas.height * 0.6
let xa = 0
let ya = Math.random() * 2 - 1
dots.push({
x: x,
y: y,
xa: xa,
ya: ya / 10,
color: getRandomColor(),
radius: getRandomNumber(1, 3)
})
}
const animate = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height)
dots.forEach((dot) => {
dot.y += dot.ya
dot.xa *= dot.x > canvas.width || dot.x < 0 ? -1 : 1
dot.ya *= dot.y > canvas.height || dot.y < 0 ? -1 : 1
ctx.fillStyle = dot.color
ctx.beginPath()
ctx.arc(dot.x - 0.5, dot.y - 0.5, dot.radius, 0, Math.PI * 2)
ctx.fill()
ctx.closePath()
})
window.requestAnimationFrame(animate)
}
animate()
})
</script>
<style lang="less" scoped>
#background {
width: 100%;
height: 100%;
}
</style>