html实现自定义的《黑客帝国》AC数字雨效果
将以下代码保存为.html
文件,在浏览器中打开。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Matrix AC Rain</title>
<style>
* { margin: 0; padding: 0; }
body { background: black; }
canvas { display: block; }
</style>
</head>
<body>
<canvas id="c"></canvas>
<script>
const c = document.getElementById("c");
const ctx = c.getContext("2d");
// 设置画布为1:1比例(例如1000x1000像素)
c.height = 1200;
c.width = 2000;
// 仅使用“AC”字符
const matrix = "AC";
const chars = matrix.split("");
const font_size = 30; //设置字体大小
const columns = c.width / font_size;
const drops = [];
// 初始化每个列的Y坐标
for (let x = 0; x < columns; x++) {
drops[x] = 1;
}
function draw() {
// 半透明黑色背景,创建拖尾效果
ctx.fillStyle = "rgba(0, 0, 0, 0.05)";
ctx.fillRect(0, 0, c.width, c.height);
// 设置荧光绿色文字
ctx.fillStyle = "#00FF00";
ctx.font = font_size + "px monospace";
// 绘制字符
for (let i = 0; i < drops.length; i++) {
const text = chars[Math.floor(Math.random() * chars.length)];
ctx.fillText(text, i * font_size, drops[i] * font_size);
// 当字符超出画布高度时,随机重置到顶部
if (drops[i] * font_size > c.height && Math.random() > 0.975) {
drops[i] = 0;
}
drops[i]++;
}
}
每33ms绘制一次,模拟动画
setInterval(draw, 33);
// 自动截图(需浏览器支持)
setTimeout(() => {
const link = document.createElement('a');
link.download = 'matrix_ac_rain.png';
link.href = c.toDataURL();
link.click();
}, 5000); // 5秒后自动下载图片
</script>
</body>
</html>
使用说明:
画布尺寸已设置为1200x2000像素。
代码仅使用“A”和“C”字符,背景为黑色,文字为荧光绿色(#00FF00)。
动画运行5秒后会自动下载为PNG图片。
如果需要调整:
修改font_size
以改变字符大小。
修改c.height
和c.width
以调整画布尺寸。
调整setInterval(draw, 33)
中的33ms
以改变动画速度。
导出图片:
浏览器会自动下载图片,或你可手动右键画布保存为PNG。
如果需要更高分辨率,增加c.height
和c.width
(如2000x2000)。
好使,不错