以下是几种实现黑客帝国风格“数字雨”效果的代码生成器及使用方法,涵盖多种编程语言与工具,零基础用户也可快速实现炫酷效果:
一、网页版数字雨(HTML+JavaScript)
特点:无需安装环境,复制代码即可运行,支持全屏动态效果,颜色可自定义。
html
canvas { background: 000; }
const canvas = document.getElementById('matrix');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const chars = '01ABCDEFGHIJKLMNOPQRSTUVWXYZ@$%^&';
const fontSize = 14;
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) => {
ctx.fillText(chars[Math.floor(Math.random chars.length)], i fontSize, drop fontSize);
if (drop fontSize > canvas.height && Math.random > 0.975) drops[i] = 0;
drops[i]++;
});
setInterval(draw, 50);
使用步骤:复制代码保存为`.html`文件,双击用浏览器打开即可看到全屏数字雨。
二、Python版数字雨(Pygame库)
特点:适合进阶用户,支持自定义字符颜色和下坠速度。
python
import pygame, random, sys
pygame.init
screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
font = pygame.font.SysFont('arial', 20)
clock = pygame.time.Clock
drops = [{'x': x20, 'y':0, 'speed': random.randint(1,5)}
for x in range(screen.get_width//20)]
while True:
screen.fill((0,0,0))
for event in pygame.event.get:
if event.type == pygame.QUIT: sys.exit
for drop in drops:
text = font.render(str(random.choice('0123456789')), True, (0,255,0))
screen.blit(text, (drop['x'], drop['y']))
drop['y'] += drop['speed']
if drop['y'] > screen.get_height:
drop['y'] = 0
pygame.display.update
clock.tick(30)
依赖安装:需安装`pygame`库(命令:`pip install pygame`),保存为`.py`运行。
三、C语言版数字雨(EasyX图形库)
特点:Windows平台专属,模拟电影级效果。
include
include
define STR_LEN 20
struct Rain { int x, y, speed; char str[STR_LEN]; } rains[100];
void initRain {
for (int i=0; i<100; i++) {
rains[i].x = i15;
rains[i].y = rand%getheight;
rains[i].speed = rand%3 + 1;
for (int j=0; j rains[i].str[j] = rand