HTML实现黑客帝国字母雨效果

HTML实现字母雨的思路:

  1. HTML部分:包含一个<canvas>元素用来绘制字母雨。
  2. CSS部分:设置基本样式,使页面背景为黑色,隐藏滚动条,并确保<canvas>全屏显示。
  3. 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>

  • 15
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值