canvas实现代码雨效果

前言

canvas绘图是一种比较常用的前端技术,适用场景包括:画板、游戏、动画、图表、视频等。下面我们使用该技术完成一个代码雨效果。

项目体验地址: canvas实现代码雨效果

核心代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const canvas = document.getElementById('canvas');
const animationInterval: number | null = null;

// 预留参数用于后续可以自定义动画内容
function rainCode(rainCodeStr="TSDJXHS1010",fillStyle='#22C55E') {
const width = window.innerWidth;
const height = window.innerHeight;
rainCodeStr = rainCodeStr?.toUpperCase() ||'TSDJXHS1010' ;
const rainCodeArr = rainCodeStr.split('');
canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
let positionY = Array.from({ length: width / 15 }, () => 0);
const colors = ['#rgb(234, 5, 250)', 'rgb(106, 6, 194)', 'rgb(19, 6, 194)', 'rgb(6, 194, 62)', 'rgb(168, 218, 19)'];
animationInterval = setInterval(() => {

ctx!.fillStyle = 'rgba(0,0,0,0.05)';
ctx!.fillRect(0, 0, width, height);
ctx!.fillStyle = fillStyle ||'#0f0'

ctx!.font = '15px Arial';
for (let i = 0; i < positionY.length; i++) {
ctx!.fillText(rainCodeArr[Math.floor(Math.random() * rainCodeArr.length)], i * 15, positionY[i]);
positionY[i] = positionY[i] > height || positionY[i] > Math.random() * 10000 ? 0 : positionY[i] + 15;
}
}, 50);

document.body.appendChild(canvas);
}

// 确保文档加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
document.body.style.margin = "0px";
document.body.style.padding = "0px";
rainCode();
});

document.addEventListener("beforeunload", () => {
animationInterval && clearInterval(animationInterval);
canvas && canvas.remove();
});
文章作者: Sir_Liu
文章链接: https://gofugui.github.io/2025/05/25/canvas实现代码雨效果/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Coding Your Life