css动画 - 2.代码雨

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>代码雨效果 - l i y l</title>
    <style>
        body {
            margin: 0;
            overflow: hidden;
            background: black;
        }

        canvas {
            display: block;
        }
    </style>
</head>

<body>
    <canvas id="matrixRain"></canvas>
    <script>
        const canvas = document.getElementById('matrixRain');
        const ctx = canvas.getContext('2d');

        // 设置画布宽高为浏览器窗口大小
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        // 文字雨的字符集
        const chars = 'Liyl';
        const matrix = chars.split('');

        const fontSize = 16;
        const columns = canvas.width / fontSize; // 字符列数
        const drops = [];

        for (let i = 0; i < columns; i++) {
            drops[i] = 1; // 初始 y 位置
        }

        function getRandomColor() {
            const letters = '0123456789ABCDEF';
            let color = '#';
            for (let i = 0; i < 6; i++) {
                color += letters[Math.floor(Math.random() * 16)];
            }
            return color;
        }

        function draw() {
            ctx.fillStyle = 'rgba(0, 0, 0, 0.05)'; // 轻微的黑色背景
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            ctx.font = `${fontSize}px monospace`;

            for (let i = 0; i < drops.length; i++) {
                const text = matrix[Math.floor(Math.random() * matrix.length)];
                ctx.fillStyle = getRandomColor(); // 设置随机颜色
                ctx.fillText(text, i * fontSize, drops[i] * fontSize);

                // 重置 y 位置,产生随机的下落速度
                if (drops[i] * fontSize > canvas.height && Math.random() > 0.975) {
                    drops[i] = 0;
                }

                drops[i]++;
            }
        }

        setInterval(draw, 33); // 每 33ms 重绘一次画布

        // 监听窗口大小变化,调整画布大小
        window.addEventListener('resize', () => {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
        });
    </script>
</body>

</html>

代码详解:

1. HTML 部分

<canvas id="matrixRain"></canvas>
  • 这是一个 HTML5 <canvas> 元素,id="matrixRain" 用于 JavaScript 中获取这个画布并操作它。
  • <canvas> 允许你通过 JavaScript 动态绘制图像、文本或图形。

2. CSS 部分

body {
    margin: 0;
    overflow: hidden;
    background: black;
}
canvas {
    display: block;
}
  • margin: 0:去掉页面默认的外边距。
  • overflow: hidden:确保当字符雨在屏幕之外时不显示滚动条。
  • background: black:背景设置为黑色,模拟代码雨的黑夜场景。
  • canvasdisplay: block:让 <canvas> 元素不受其他元素影响,并独立占据整块区域。

3. JavaScript 部分

初始化画布
const canvas = document.getElementById('matrixRain');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
  • 获取 <canvas> 元素,并通过 getContext('2d') 获取绘制 2D 图形的上下文。
  • 设置画布的宽度和高度与浏览器窗口大小一致。
设置字符和下落位置
const chars = 'Liyl';
const matrix = chars.split(''); // 将字符串分割为数组
const fontSize = 16;
const columns = canvas.width / fontSize; // 计算列数
const drops = [];
for (let i = 0; i < columns; i++) {
    drops[i] = 1; // 初始化每列的字符 y 位置
}
  • chars = 'Liyl' 定义了字符雨中显示的字符集,可以根据需要替换。
  • matrix = chars.split('') 将字符集分割成单个字符数组。
  • fontSize = 16 定义字符的字体大小。
  • columns 计算字符列数,这样可以在每列中控制字符下落。
  • drops[] 用于跟踪每一列中字符的垂直位置(y 坐标)。
随机生成颜色
function getRandomColor() {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}
  • 生成随机颜色,字符会以随机颜色绘制在画布上。
绘制和更新字符雨
function draw() {
    ctx.fillStyle = 'rgba(0, 0, 0, 0.05)'; // 透明的黑色背景,留下轻微的尾迹
    ctx.fillRect(0, 0, canvas.width, canvas.height); // 绘制全屏黑色背景

    ctx.font = `${fontSize}px monospace`;

    for (let i = 0; i < drops.length; i++) {
        const text = matrix[Math.floor(Math.random() * matrix.length)]; // 随机选择字符
        ctx.fillStyle = getRandomColor(); // 随机颜色
        ctx.fillText(text, i * fontSize, drops[i] * fontSize); // 绘制字符

        // 如果字符雨超出了画布高度,或者随机概率触发,重置位置
        if (drops[i] * fontSize > canvas.height && Math.random() > 0.975) {
            drops[i] = 0;
        }
        drops[i]++; // 让字符下移
    }
}
setInterval(draw, 33); // 每33毫秒刷新一次画布
  • ctx.fillStyle 设置为 rgba(0, 0, 0, 0.05),这使得每次重绘时画布上有少量透明背景,形成“拖影”效果。
  • ctx.fillRect 重新绘制背景,以产生重影效果。
  • 随机从 matrix 数组中选择字符,并以随机颜色绘制。
  • 字符一旦超出画布高度,或者概率条件满足,则重置下落位置。
监听窗口大小变化
window.addEventListener('resize', () => {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
});
  • 当浏览器窗口大小变化时,调整画布的宽度和高度,以适应新的窗口尺寸。

使用步骤

  1. 复制代码:将代码复制到你自己创建的 .html 文件中。
  2. 在浏览器中打开:双击 .html 文件,或在浏览器中通过 file:// 路径打开。
  3. 调整字符集:你可以修改 const chars = 'Liyl'; 这一行,将字符集更改为你想要的任何字符。
  4. 修改颜色效果:如果你希望字符以特定颜色显示,可以修改 getRandomColor() 方法,或直接设置 ctx.fillStyle 为固定颜色。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值