js實現黑客帝國數字雨效果 效果圖 代碼

效果圖

代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
      body {
        margin: 0;
        padding: 0;
      }
      canvas {
        width: 100%;
        height: 100%;
      }
    </style>
  </head>
  <body>
    <canvas style="background:#111"></canvas>

    <script>
      //獲取畫布對象
      var can = document.querySelector("canvas");
      //獲取畫布的上下文
      var ctx = can.getContext("2d");
      //設置canvas的寬度和高度
      can.width = window.innerWidth;
      can.height = window.innerHeight;
      //每個文字的字體大小
      var fontSize = 16;
      //計算列
      var colunms = Math.floor(window.innerWidth / fontSize);
      //記錄每列文字的y軸座標
      var arr = [];
      //給每一個文字初始化一個起始點的位置
      for (var i = 0; i < colunms; i++) {
        arr.push(0);
      }
      //運動的文字
      var str = "you are a silly";
      //繪畫的函數
      function draw() {
        //佈滿全屏的黑色遮罩層
        ctx.fillStyle = "rgba(0,0,0,0.05)";
        ctx.fillRect(0, 0, window.innerWidth, window.innerHeight);
        //給字體設置樣式
        ctx.font = "700 " + fontSize + "px  微軟雅黑";
        //給字體添加顏色
        ctx.fillStyle = "#00cc33";
        //寫入畫布中
        for (var i = 0; i < colunms; i++) {
          var index = Math.floor(Math.random() * str.length);
          var x = i * fontSize;
          var y = arr[i] * fontSize;
          ctx.fillText(str[index], x, y);
          //如果文字的Y軸座標大於畫布的高度,1/100*colunms概率將該文字的Y軸座標重置爲0
          if (y >= can.height && Math.random() > 0.99) {
            arr[i] = 0;
          }
          //文字Y軸座標+1
          arr[i]++;
        }
      }
      draw();
      setInterval(draw, 30);
    </script>
  </body>
</html>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章