マトリックス風背景を作ってみた

<link href="https://fonts.googleapis.com/css2?family=Share+Tech+Mono&display=swap" rel="stylesheet">
<canvas id="matrix" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: -1;"></canvas>

<script>
  const canvas = document.getElementById('matrix');
  const ctx = canvas.getContext('2d');

  function resizeCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
  }

  resizeCanvas();
  window.addEventListener('resize', resizeCanvas);

  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}|;:,.<>/?`~';
  const charArray = characters.split('');
  let fontSize = Math.max(12, window.innerWidth / 100);
  let columns = Math.floor(canvas.width / fontSize);
  let drops = Array.from({ length: columns }, () => Math.random() * canvas.height / fontSize);

  function getRandomChar() {
    const rand = new Uint32Array(1);
    crypto.getRandomValues(rand);
    return charArray[rand[0] % charArray.length];
  }

  function draw() {
    ctx.fillStyle = 'rgba(0, 0, 0, 0.05)';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.font = fontSize + "px 'Share Tech Mono', monospace";

    for (let i = 0; i < drops.length; i++) {
      const text = getRandomChar();
      const x = i * fontSize;
      const y = drops[i] * fontSize;

      // 光る1文字
      ctx.shadowColor = '#0F0';
      ctx.shadowBlur = 10;
      ctx.fillStyle = '#0F0';
      ctx.fillText(text, x, y);

      // 残像を描画(1つ前の位置)
      ctx.shadowBlur = 0;
      ctx.fillStyle = 'rgba(0, 255, 0, 0.3)';
      ctx.fillText(text, x, y - fontSize);

      // 落下管理
      if (y > canvas.height && Math.random() > 0.975) {
        drops[i] = 0;
      } else {
        drops[i]++;
      }
    }
  }

  function animate() {
    draw();
    requestAnimationFrame(animate);
  }

  animate();
</script>

コメント

タイトルとURLをコピーしました