css特效之数字雨

效果预览:效果预览
源码下载:关注公众号【RMRF】,回复【css13】可获取源码

1、使用<canvas>元素创建了一个画布,用于绘制数字雨的效果
2、创建一个数组 arrs 来记录每一列的位置
3、并用随机的绿色和字体大小来绘制随机数字,同时更新 arrs 数组,模拟数字的下落
4、如果数字下落到底部或达到一定概率,重置数字位置

HTML

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>数字雨</title>
  <style>
    /* 清除所有元素的内外边距 */
    * {
      padding: 0px;
      margin: 0px;
    }

    /* 设置页面样式 */
    body {
      height: 100vh;
      width: 100vw;
      overflow: hidden;
      background: #000;
    }
  </style>
</head>

<body>
  <!-- 创建画布元素 -->
  <canvas id="canvas"></canvas>
</body>
<script>
</script>

</html>

JavaScript

const canvas = document.getElementById("canvas")
  const ctx = canvas.getContext("2d")
  const fontSize = 20
  let rows, columns, arrs

  // 自适应
  function resizeCanvas() {
    const width = window.innerWidth || document.documentElement.clientWidth
    const height = window.innerHeight || document.documentElement.clientHeight
    canvas.width = width
    canvas.height = height
    rows = Math.ceil(height / fontSize)
    columns = Math.ceil(width / fontSize)
    arrs = new Array(columns).fill(0)
  }

  // 动画
  function animation() {
    ctx.fillStyle = "rgba(0,0,0,0.1)"
    ctx.fillRect(0, 0, canvas.width, canvas.height)
    for (let i = 0; i < columns; i++) {
      ctx.fillStyle = "green"
      ctx.font = `${fontSize}px 宋体`
      ctx.fillText(Math.floor(Math.random() * 10), fontSize * i, arrs[i] * fontSize)
      arrs[i]++
      if (arrs[i] > rows || Math.random() > 0.98) {
        arrs[i] = 0
      }
    }
    setTimeout(() => {
      animation()
    }, 20)
  }
  
  // 初始化
  function init() {
    resizeCanvas()
    window.addEventListener("resize", resizeCanvas)
    animation()
  }
  init()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值