用canvas写一个动态的代码雨背景页面

415 阅读1分钟

用canvas写一个动态的代码雨背景页面

1.png

话不多说直接上代码(每一步的注释都非常详细):

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>code rain effect</title>
  <style>
    body{
      background-color: black;
    }
    #bg{
      width: 100%;
      height: 100%;
    }
  </style>
</head>
<body>
  <canvas id="bg"></canvas>

  <script type="text/javascript">
    const cvs = document.getElementById('bg'); // 获取canvas元素
    const height = window.innerHeight, width = window.innerWidth; // 页面的窗口尺寸
    /* 设置canvas的宽高 */
    cvs.width = width;
    cvs.height = height;

    // 获取绘制上下文
    const ctx = cvs.getContext('2d');

    // 设置文字列宽
    const columnWidth = 20;
    // 设置文字列数(canvas的宽度(窗口宽度)/列宽)
    const columnNumber = Math.floor(width / columnWidth);
    // 创建数组记录每列写到第几个文字, 文字的列数有多少这个数组的长度就有多少
    const recordList = new Array(columnNumber);
    // 给数组填充都为1
    recordList.fill(1);
    // 随机的颜色
    function randomColor() {
      var color = "#";
      //for循环中,如果后面仅有一条语句,{}可省略不写
      //随机生成6位0-15之间的数字,再用toString(16)将数字转成16进制
      for (var i = 0; i < 6; i++) color += parseInt(Math.random() * 16).toString(16);
      return color;
    };

    // 随机的文字
    function randomString(){
      let str = '(Hello)!IAmRandomRtring~'
      return str[Math.floor(Math.random()*str.length)]
    };

    // 绘制函数
    function draw(){
      ctx.fillStyle = 'rgba(0, 0, 0, 0.1)'; // 让上面的文职漫漫变模糊(颜色根据你的背景颜色来)
      ctx.fillRect(0, 0 , width, height);
      const fz = 22; // 字体大小
      ctx.fillStyle = randomColor(); // 设置字体颜色
      ctx.fontSize = fz + 'px'; // 设置字体大小, 以及字体样式
      for(let i = 0; i < recordList.length; i++){
        const x = i * columnWidth; // x坐标为它的列数 * 列宽
        const y = fz * recordList[i] // y坐标为它字体的高度 * 它这一列的下一个文字的数字
        ctx.fillText(randomString(), x, y);
        // 绘制一次, 记录数组recordList里的值就要+1
        recordList[i]++;
        if(y >= height && Math.random() < 0.08) recordList[i] = 0; //如果y坐标大于高度就归0, Math.random() < 0.08由于随机数的原因就会每一列归0不一样就像下雨一样了
      };
    };

    setInterval(draw, 30)


  </script>
</body>

</html>

当然随机的颜色你可以自己去指定几种颜色通过Math.random()函数从你指定的颜色数组获取颜色