js实现代码雨
实现代码雨效果
使用HTML5 Canvas和JavaScript可以轻松实现经典的代码雨效果。以下是完整的实现代码和说明:

HTML结构
<!DOCTYPE html>
<html>
<head>
<title>代码雨效果</title>
<style>
body {
margin: 0;
overflow: hidden;
background: black;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="script.js"></script>
</body>
</html>
JavaScript实现
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 设置画布大小为窗口大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 定义字符集
const chars = "01";
const fontSize = 16;
const columns = canvas.width / fontSize;
// 初始化雨滴数组
const rainDrops = [];
for (let i = 0; i < columns; i++) {
rainDrops[i] = 1;
}
// 绘制函数
function draw() {
// 半透明黑色背景
ctx.fillStyle = 'rgba(0, 0, 0, 0.05)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 设置字体和颜色
ctx.fillStyle = '#0F0';
ctx.font = fontSize + 'px monospace';
// 绘制每个雨滴
for (let i = 0; i < rainDrops.length; i++) {
const text = chars.charAt(Math.floor(Math.random() * chars.length));
ctx.fillText(text, i * fontSize, rainDrops[i] * fontSize);
// 随机重置雨滴位置
if (rainDrops[i] * fontSize > canvas.height && Math.random() > 0.975) {
rainDrops[i] = 0;
}
rainDrops[i]++;
}
}
// 动画循环
setInterval(draw, 30);
// 窗口大小调整时重置画布
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
自定义选项
可以通过修改以下参数来自定义效果:
- 更改
chars变量使用不同的字符集 - 调整
fontSize改变字符大小 - 修改
ctx.fillStyle改变文字颜色 - 调整
setInterval的时间间隔控制动画速度
高级优化版本
更复杂的实现可以包含以下特性:
// 添加渐变颜色效果
const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
gradient.addColorStop(0, '#0F0');
gradient.addColorStop(0.5, '#0A0');
gradient.addColorStop(1, '#050');
ctx.fillStyle = gradient;
// 添加随机速度
const speeds = [];
for (let i = 0; i < columns; i++) {
speeds[i] = 1 + Math.random() * 3;
}
// 在draw函数中使用速度
rainDrops[i] += speeds[i] / 10;
实现原理
代码雨效果的核心原理是利用Canvas API不断绘制和更新字符位置。通过半透明的背景叠加产生拖尾效果,随机字符和位置重置创造下雨的视觉感受。调整参数可以产生不同风格的数字雨效果。







