以下整理了几种快速生成黑客帝国风格“代码雨”特效的方法及代码片段,涵盖HTML、JavaScript、Python等多种实现方式,一键复制即可运行,适合编程展示或个性化桌面效果:
一、HTML + JavaScript 实现(最简版)
代码示例(复制到`.html`文件运行):
html
body { margin: 0; overflow: hidden; background: black; }
const canvas = document.getElementById('matrix');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const chars = '01ABCDEFGHIJKLMNOPQRSTUVWXYZ@$%^&'; // 可自定义字符集
const fontSize = 16;
const columns = canvas.width / fontSize;
const drops = Array(Math.floor(columns)).fill(0);
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';
drops.forEach((drop, i) => {
const char = chars[Math.floor(Math.random chars.length)];
ctx.fillText(char, i fontSize, drop);
drops[i] = drop > canvas.height || Math.random > 0.95 ? 0 : drop + 10;
});
setInterval(draw, 50); // 速度调节:数值越小下落越快
效果特点:自适应屏幕、绿色字符雨、动态模糊轨迹。
二、Python + Pygame 实现(终端运行版)
代码示例(需安装`pygame`库):
python
import pygame, random
pygame.init
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock
chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
font = pygame.font.SysFont('consolas', 15)
def create_code:
return random.choice(chars)
codes = [{'x': random.randint(0,800), 'y': random.randint(-600,0), 'char': create_code} for _ in range(100)]
running = True
while running:
screen.fill((0,0,0))
for event in pygame.event.get:
if event.type == pygame.QUIT:
running = False
for code in codes:
text = font.render(code['char'], True, (0,255,0))
screen.blit(text, (code['x'], code['y']))
code['y'] += 5 下落速度
if code['y'] > 600:
code.update({'y':0, 'x': random.randint(0,800), 'char': create_code})
pygame.display.update
clock.tick(30) 帧率控制
效果特点:可调节字符密度、速度,支持自定义字体颜色(如改为霓虹蓝)。
三、在线生成工具(零代码)
访问 [代码雨特效生成工具](https://www.wqtool.com/coderain),直接通过可视化界面调整参数:
四、进阶装X技巧
1. 字符扩展:替换`chars`变量为片假名(如`アァカサタナ`)或汉字,模仿电影原版效果。
2. 颜色渐变:在JavaScript中使用`ctx.fillStyle = 'hsl(' + hue + ', 100%, 50%)';`实现彩虹渐变。
3. 音效增强:添加键盘敲击声背景音(需加载音频文件)。
一键运行提示:
将HTML代码保存为`.html`文件后双击打开,或使用Python运行脚本(需安装依赖库)。修改代码中的字符、颜色、速度参数可打造个性化“数字矩阵”效果。