0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

o1 + canvasでマトリックスのような雨をふらしてみた

Posted at

この記事では、HTML の <canvas> 要素を使って、いわゆる「マトリックスの雨」のような画面エフェクトを作ってみた話を紹介します。
といっても、複雑な仕組みは使わず、JavaScript でシンプルなアニメーションを書くだけです。

実際の動画

以下の動画(あるいは GIF)で実際の動きをご覧ください。

コード例

シンプルに実装すると、以下のようなコードになります。お好みでカスタマイズしてみてください。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Matrix Rain Effect</title>
    <style>
        body {
            margin: 0;
            overflow: hidden;
            background: black;
        }
        canvas {
            display: block;
        }
    </style>
</head>
<body>
    <canvas id="matrixCanvas"></canvas>

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

        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        const fontSize = 16;
        const columns = Math.floor(canvas.width / fontSize);
        const drops = Array(columns).fill(0);

        const characters = 'アカサタナハマヤラワイキシチニヒミリウクスツヌフムユルエケセテネヘメレオコソトノホモヨロ';

        function drawMatrixRain() {
            ctx.fillStyle = 'rgba(0, 0, 0, 0.05)';
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            ctx.fillStyle = '#0F0';
            ctx.font = `${fontSize}px monospace`;

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

                ctx.fillText(text, x, y);

                if (y > canvas.height && Math.random() > 0.95) {
                    drops[i] = 0;
                }

                drops[i]++;
            }
        }

        setInterval(drawMatrixRain, 50);

        window.addEventListener('resize', () => {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
            drops.length = Math.floor(canvas.width / fontSize);
            drops.fill(0);
        });
    </script>
</body>
</html>

ポイント解説

  • characters: 自由に文字列をアレンジ可能です。日本語、アルファベット、数字、記号など好きに追加してみてください。
  • 残像エフェクト: rgba(0, 0, 0, 0.05) で描画することで、前フレームをわずかに残す「トレイル」感が出ます。
  • 乱数の使い方: Math.random() > 0.975 など、確率を使ってランダムにリセットすることで、雨が断続的に降り続けるように演出しています。

まとめ

以上、「キャンバスでマトリックスのような雨のエフェクトを作る」簡単な例でした。
スクリーンショットや動画を Zenn 上に追加するだけでも、記事として見やすくなると思います。
お好みでフォントサイズや速度を変えたり、色をカスタマイズして遊んでみてください。


0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?