代码雨实现vue
实现代码雨效果(Vue版)
使用Vue实现代码雨效果可以通过Canvas绘制结合动画帧实现。以下是完整实现方案:
核心代码结构
<template>
<div class="code-rain-container">
<canvas ref="canvas"></canvas>
</div>
</template>
<script>
export default {
data() {
return {
chars: "01",
fontSize: 16,
columns: 0,
drops: [],
animationFrame: null
}
},
mounted() {
this.initCanvas()
window.addEventListener('resize', this.handleResize)
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
cancelAnimationFrame(this.animationFrame)
},
methods: {
initCanvas() {
const canvas = this.$refs.canvas
const ctx = canvas.getContext('2d')
canvas.width = window.innerWidth
canvas.height = window.innerHeight
this.columns = Math.floor(canvas.width / this.fontSize)
this.drops = Array(this.columns).fill(1)
this.draw()
},
draw() {
const canvas = this.$refs.canvas
const ctx = canvas.getContext('2d')
ctx.fillStyle = 'rgba(0, 0, 0, 0.05)'
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.fillStyle = '#0F0'
ctx.font = `${this.fontSize}px monospace`
for (let i = 0; i < this.drops.length; i++) {
const text = this.chars[Math.floor(Math.random() * this.chars.length)]
ctx.fillText(text, i * this.fontSize, this.drops[i] * this.fontSize)
if (this.drops[i] * this.fontSize > canvas.height && Math.random() > 0.975) {
this.drops[i] = 0
}
this.drops[i]++
}
this.animationFrame = requestAnimationFrame(this.draw)
},
handleResize() {
cancelAnimationFrame(this.animationFrame)
this.initCanvas()
}
}
}
</script>
<style>
.code-rain-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #000;
z-index: -1;
}
canvas {
display: block;
}
</style>
自定义参数调整
修改数据属性可调整效果:

data() {
return {
chars: "01ABCDEFGHIJKLMNOPQRSTUVWXYZ", // 可显示字符
fontSize: 18, // 字体大小
speed: 1, // 下落速度系数
opacity: 0.05 // 背景透明度
}
}
性能优化方案
对于大屏幕设备,可添加节流处理:

handleResize: _.throttle(function() {
cancelAnimationFrame(this.animationFrame)
this.initCanvas()
}, 200)
组件化使用方式
- 创建
CodeRain.vue文件并粘贴上述代码 - 在需要使用的组件中引入:
import CodeRain from './components/CodeRain.vue' export default { components: { CodeRain } } - 在模板中使用:
<code-rain />
效果增强技巧
添加渐变颜色效果:
const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height)
gradient.addColorStop(0, '#0F0')
gradient.addColorStop(0.5, '#0C0')
gradient.addColorStop(1, '#090')
ctx.fillStyle = gradient
实现字符颜色变化:
ctx.fillStyle = `hsl(${Math.random() * 120 + 60}, 100%, 50%)`






