js canvas黑客帝国文字雨特效

2023-03-13  本文已影响0人  IamaStupid

canvas黑客帝国文字雨特效

<canvas id="myCanvas"></canvas>
    <!-- built files will be auto injected -->
    <script>
      var $cvs=document.getElementById("myCanvas");
      var ctx=$cvs.getContext("2d");

      let ww = 500;
      let hh = 400;

      $cvs.width = ww;
      $cvs.height = hh;

      let fontSize = 14;
      let columMax = Math.floor(ww / fontSize);
      ctx.font=`${fontSize}px Arial`;
      ctx.textBaseline = "top";
      let rowIndex = 0;
      let drop = []

      let tt;

      animateText()

      function animateText() {
        drawText()
        // window.requestAnimationFrame(() => {
        //   animateText()
        // })
        tt = setTimeout(() => {
          animateText()
        }, 100)
      }

      function drawText() {
        ctx.fillStyle = "rgba(0, 0, 0, 0.1)";
        ctx.fillRect(0,0,$cvs.width,$cvs.height);
        ctx.fillStyle="#0F0";
        for(let i = 0; i < columMax; i++) {
          let text = getRandomText();
          if (drop[i] === undefined) {
            // 第一次初始化的时候,给文字的y坐标设一个随机数
            drop[i] = Math.floor(Math.random() * hh/4);
          } else if(drop[i] >= hh || (drop[i] >= (hh/4) && Math.random() > 0.9)) {
            // 文字的Y坐标超过了canvas的高度 或者
            // 随机数大于0.9,则重新个y坐标赋值
            drop[i] = 0;
          } else {
            drop[i] = drop[i] + fontSize;
          }
          ctx.fillText(text, i * fontSize, drop[i]);
        }
      }
      function getRandomText() {
        let randomStr = '0sd0ldpqwoe2xnvhb9zdka3dj4apwien7a58ubgur60adb';
        return randomStr[Math.floor(Math.random() * randomStr.length)]
      }
    </script>
```js
上一篇下一篇

猜你喜欢

热点阅读