html数字雨

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>数字雨</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
            background: #000000;
        }
    </style>
</head>
<body>
<canvas id="digitalRain">
</canvas>
<script>

  根据id获取画布

const cvs = document.getElementById("digitalRain");

  获取屏幕的宽高

   const width = window.screen.width;
   const height = window.screen.height;

 画布宽高设置要和屏幕一样大

 cvs.width = width;
 cvs.height = height;

 获取画笔

const ctx = cvs.getContext("2d");

 每个数字的大小

 const fontSize = 20;

 整个屏幕能显示多少行数字

 整个屏幕能显示多少列数字

const rows = Math.ceil(height / fontSize);
const columns = Math.ceil(width / fontSize)

 定义数组保存多列数字当前所处第几行,初始值在第 0 行

const lines = new Array(columns).fill(0);

 定时调用里面的代码

setInterval(() => {
        // 每次调用之前,都用一个不太透明的矩形遮挡整个画布
        ctx.fillStyle = "rgba(0,0,0,0.1)"
        ctx.fillRect(0, 0, width, height)

 循环绘制多列数字

 for (let i = 0; i < columns; i++) {
            // 画一个字符
            ctx.fillStyle = "white";
            ctx.font = fontSize + "px 宋体";
            ctx.fillText(Math.floor(Math.random()*10)+"", i * fontSize, lines[i] * fontSize);
            // 每次都增加当前列数字在数组中对应的行的值
            lines[i]++;

            // 如果当前数字所处的行大于最大行数,那么就把行数设置为 0 ,这样数字就返回顶部重新掉落
            // Math.random() > 0.95 作用是让极小一部分数字在没有掉落到底部之前回到顶部
            if (lines[i] > rows || Math.random() > 0.95) {
                lines[i] = 0;
            }
        }

    }, 30)

</script>
</body>
</html>

 结果运行:

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值