当前位置:首页 > 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;
});

效果增强技巧

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

js实现代码雨

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

添加渐变色效果:

js实现代码雨

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();

添加帧率控制:

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实现分页

实现分页的基本思路 分页功能通常需要处理数据分割、页码生成和用户交互。核心逻辑包括计算总页数、根据当前页截取数据、渲染页码按钮等。 前端分页实现(静态数据) 假设已有全部数据,仅需前端分页展示:…

vue本地查询代码实现

vue本地查询代码实现

Vue 本地查询代码实现 在Vue中实现本地查询功能,可以通过以下几种方式实现,具体取决于数据源和查询需求。 使用计算属性进行本地查询 计算属性是Vue中处理响应式数据查询的高效方式,适合基于现有数…

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js如何实现继承

js如何实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例能够访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

js分组实现

js分组实现

分组实现方法 在JavaScript中,可以通过多种方式实现数组或对象的分组操作。以下是几种常见的方法: 使用Array.prototype.reduce() 通过reduce方法可以轻松实现数组分…

js实现自举

js实现自举

实现 JavaScript 自举的方法 JavaScript 自举(Bootstrap)通常指通过 JavaScript 动态加载自身或依赖的脚本,实现运行时环境的初始化或扩展。以下是几种常见实现方式…