当前位置:首页 > JavaScript

js实现代码雨

2026-04-03 21:07:00JavaScript

实现思路

使用HTML5的Canvas元素结合JavaScript动态生成代码雨效果。核心原理是创建多个垂直下落的字符,模拟《黑客帝国》中的经典场景。

HTML结构

<!DOCTYPE html>
<html>
<head>
    <title>代码雨</title>
    <style>
        body {
            margin: 0;
            overflow: hidden;
            background: black;
        }
        canvas {
            display: block;
        }
    </style>
</head>
<body>
    <canvas id="canvas"></canvas>
    <script src="script.js"></script>
</body>
</html>

JavaScript实现

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

const chars = "01";
const fontSize = 16;
const columns = canvas.width / fontSize;
const drops = [];

for (let i = 0; i < columns; i++) {
    drops[i] = 1;
}

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';

    for (let i = 0; i < drops.length; i++) {
        const text = chars[Math.floor(Math.random() * chars.length)];
        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);

window.addEventListener('resize', () => {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
});

效果增强技巧

修改字符集可以增加多样性:

const chars = "01アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲン";

添加渐变色效果:

const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
gradient.addColorStop(0, '#0F0');
gradient.addColorStop(1, '#0A0');
ctx.fillStyle = gradient;

性能优化

使用requestAnimationFrame替代setInterval:

function animate() {
    draw();
    requestAnimationFrame(animate);
}
animate();

添加帧率控制:

js实现代码雨

let lastTime = 0;
const fps = 30;
const fpsInterval = 1000 / fps;

function animate(timeStamp) {
    if (timeStamp - lastTime > fpsInterval) {
        lastTime = timeStamp;
        draw();
    }
    requestAnimationFrame(animate);
}
animate();

标签: 代码js
分享给朋友:

相关文章

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 使用JavaScript实现拖拽功能需要监听鼠标事件,包括mousedown、mousemove和mouseup。以下是实现的基本逻辑: const draggableEleme…

js实现复制到剪贴板

js实现复制到剪贴板

使用document.execCommand方法(传统方式,已废弃但部分浏览器仍支持) 该方法适用于旧版浏览器,但已被标记为废弃。执行前需确保文本已被选中: function copyToClipb…

js实现瀑布流

js实现瀑布流

实现瀑布流布局 瀑布流布局是一种常见的网页布局方式,常用于图片展示、商品列表等场景。以下是使用 JavaScript 实现瀑布流布局的几种方法。 纯 JavaScript 实现 通过计算元素的位置和…

vue怎么实现文本代码实现

vue怎么实现文本代码实现

Vue 实现文本代码展示的方法 在 Vue 中展示代码文本通常需要结合语法高亮和格式化的功能,以下是几种常见的实现方式: 使用 <pre> 和 <code> 标签 通过 HT…

js实现点击显示和隐藏

js实现点击显示和隐藏

实现点击显示和隐藏的JavaScript方法 使用classList.toggle切换类名 通过添加/移除CSS类控制元素的显示与隐藏,需提前在CSS中定义隐藏样式(如display: none)。…

js实现防洪

js实现防洪

防抖(Debounce)实现 防抖的核心思想是在事件触发后延迟执行回调函数,若在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口调整等场景。 function debounce(f…