JavaScript Matrix Effect
How to Create the Matrix Digital Rain Effect with JavaScript
Watch the full tutorial here:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="./main.js" defer></script>
<title>Matrix Effect</title>
</head>
<body>
<canvas id="matrixCanvas"></canvas>
</body>
</html>
css
body {
margin: 0;
background: black;
overflow: hidden;
}
canvas {
display: block;
}
javascript
const canvas = document.getElementById("matrixCanvas");
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const katakana = "アァイイウエエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲン";
const latin = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const nums = "0123456789";
const alphabet = katakana + latin + nums;
const fontSize = 16;
const columns = canvas.width / fontSize;
const drops = Array(Math.floor(columns)).fill(1);
function drawMatrix() {
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 = alphabet.charAt(Math.floor(Math.random() * alphabet.length));
const x = i * fontSize;
const y = drops[i] * fontSize;
ctx.fillText(text, x, y);
if (y > canvas.height && Math.random() > 0.975) {
drops[i] = 0;
}
drops[i]++;
}
requestAnimationFrame(drawMatrix);
}
drawMatrix();
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});