Skip to content

Instantly share code, notes, and snippets.

@arnaudin
Created February 7, 2025 06:00
Show Gist options
  • Select an option

  • Save arnaudin/a5bdc1592a81883bd49965e12c8af546 to your computer and use it in GitHub Desktop.

Select an option

Save arnaudin/a5bdc1592a81883bd49965e12c8af546 to your computer and use it in GitHub Desktop.
Matrix-style digital rain falling
<!DOCTYPE html>
<html>
<head>
<title>Matrix Digital Rain</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: black;
}
#canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const chars = 'アァカサタナハマヤャラワガザダバパイィキシチニヒミリヰギジヂビピウゥクスツヌフムユュルグズブヅプエェケセテネヘメレヱゲゼデベペオォコソトノホモヨョロヲゴゾドボポヴッン1234567890QWERTYUIOPASDFGHJKLZXCVBNM';
const charArray = chars.split('');
const fontSize = 16;
const columns = canvas.width / fontSize;
const drops = [];
for (let i = 0; i < columns; i++) {
drops[i] = 1;
}
let isPaused = false;
let intervalId;
function draw() {
if (isPaused) return; // Don't draw if paused
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 = charArray[Math.floor(Math.random() * charArray.length)];
ctx.fillText(text, i * fontSize, drops[i] * fontSize);
if (drops[i] * fontSize > canvas.height && Math.random() > 0.975) {
drops[i] = 0;
}
drops[i]++;
}
}
function resetRain(){
for (let i = 0; i < drops.length; i++)
{
drops[i] = Math.floor(Math.random()*canvas.height/fontSize); //Random start on reset.
}
}
function startAnimation() {
intervalId = setInterval(draw, 33);
}
function stopAnimation() {
clearInterval(intervalId);
}
// Adjust canvas size on window resize
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const newColumns = canvas.width / fontSize;
if (newColumns > columns) {
for (let i = columns; i < newColumns; i++) {
drops[i] = Math.floor(Math.random() * canvas.height / fontSize);
}
}
// Recalculate columns
columns = newColumns;
}, false);
// Hotkey event listener
document.addEventListener('keydown', (event) => {
if (event.key === 'p' || event.key === 'P') {
isPaused = !isPaused;
if (isPaused) {
stopAnimation();
} else {
startAnimation();
}
} else if (event.key === 'r' || event.key === 'R') {
resetRain();
}
});
startAnimation();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment