この記事では、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 上に追加するだけでも、記事として見やすくなると思います。
お好みでフォントサイズや速度を変えたり、色をカスタマイズして遊んでみてください。