HTML实现字母雨的思路:
- HTML部分:包含一个
<canvas>
元素用来绘制字母雨。- CSS部分:设置基本样式,使页面背景为黑色,隐藏滚动条,并确保
<canvas>
全屏显示。- JavaScript部分:
- 获取
<canvas>
元素并设置其宽度和高度。- 定义一个包含字母和数字的字符串。
- 计算列数(每列对应一个下落的字符)。
- 初始化一个数组
drops
来存储每列字符的位置。draw
函数用于绘制字母雨:清除之前的绘制内容,设置字体样式,随机选择字母和颜色,绘制字母,并更新每列字符的位置。如果某列字符超出屏幕高度,则以一定几率重置该列位置。
效果图:
这里使用了Math.random()方法生成大于等于0小于1随机数。
Math.random() * 想生成的总值
例:生成1-10的随机数
Math.floor(Math.random() * 10)
用于向下取整的函数方法:Math.floor()
例:生成1-10的随机数取整
Math.floor(Math.random() * 10);
用于获取指定索引处的字符的方法:str.charAt()
例:生成1-10的随机数取整拿到对应的字符
letters.charAt(Math.floor(Math.random() * letters.length));
const letters ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
letters.charAt(5);//获取索引为5处的字符串‘F’
letters.charAt(12);//获取索引为5处的字符串‘M’
完整实例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body,
html {
height: 100%;
margin: 0;
overflow: hidden;
background-color: black; /* 背景色 */
}
#matrix {
display: block;
}
</style>
</head>
<body>
<canvas id="matrix"></canvas>
</body>
<script>
const canvas = document.getElementById("matrix");
//获取 canvas 元素及其上下文
const ctx = canvas.getContext("2d");
//设置 canvas 的宽度和高度为窗口的宽度和高度
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
//定义字母集合、字体大小以及列数
const letters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const fontSize = 16;
const columns = canvas.width / fontSize;
//创建一个长度为 columns 的数组,并将每个元素初始化为 1
const drops = Array.from({ length: columns }).map(() => 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`;
drops.forEach((y, i) => {
const text = letters.charAt(Math.floor(Math.random() * letters.length));
//设置随机颜色
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
ctx.fillStyle = `rgb(${r},${g},${b})`;
const x = i * fontSize;
ctx.fillText(text, x, y * fontSize);
//某列超过屏幕高度,则重置其位置
if (y * fontSize > canvas.height && Math.random() > 0.975) {
drops[i] = 0;
}
drops[i]++;
});
}
setInterval(draw, 33);
</script>
</html>