矩阵数字雨

206 阅读1分钟

效果说明

本案例实现了一个类似《黑客帝国》中的数字雨效果。字符从屏幕顶部落下,形成连续的数字流,并添加了渐变和拖尾效果。

Snipaste_2024-12-24_22-57-04.png

核心实现

1. 基础设置

// 字符配置
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; // 可选字符集
const fontSize = 16;  // 字体大小
const columns = Math.floor(canvas.width / fontSize); // 计算列数
const drops = new Array(columns).fill(1);  // 每列的当前位置

2. 渐变效果

使用线性渐变创建从亮到暗的过渡:

const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
gradient.addColorStop(0, '#0f0');    // 顶部亮绿色
gradient.addColorStop(0.2, '#0f0');  // 上部保持亮绿
gradient.addColorStop(1, '#040');    // 底部暗绿色

3. 拖尾效果实现

每个字符上方绘制5个渐隐的字符:

// 绘制字符上方的渐变拖尾效果
for (let j = 1; j <= 5; j++) {
    const tailChar = chars[Math.floor(Math.random() * chars.length)];
    const alpha = (5 - j) / 5;  // 透明度逐渐降低
    drawChar(tailChar, x, y - j * fontSize, alpha);
}

4. 背景渐隐

使用半透明黑色实现渐隐效果:

ctx.fillStyle = 'rgba(0, 0, 0, 0.05)';
ctx.fillRect(0, 0, canvas.width, canvas.height);

关键参数说明

  • fontSize: 控制字符大小和列间距
  • drops: 存储每列当前位置的数组
  • chars: 可选字符集,决定显示的字符范围
  • 背景透明度(0.05): 控制拖尾长度

Demo