Matrix Code Rain
I’ve always wanted to create this: Matrix code rain in Javascript.
Here’s the basic idea behind the animation:
- Create empty columns on the page,
- Continuously add a random character to a randomly chosen column,
- Replace columns that extend beyond the screen with new empty ones.
# Setup
-
Define our character set: half-width kana and lowercase ASCII letters:
。「」、・ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙゚
,0123456789abcdefghijklmnopqrstuvwxyz
-
Create a function that returns a random value up to its argument (used for generating random characters, selecting random columns, and determining random intervals).
# Forming columns
- Calculate how many columns fit on the screen (to ensure responsiveness),
- Add the calculated number of
<div></div>
elements to the page.
# Doing the heavy lifting
At varying random intervals, perform these steps:
- Choose a random column, append a span element with
class='new'
, - Add a random character to the new span,
- After 130 ms, change the span’s class to
old
.
The new
class signifies a newly created character, which is white. The old
class is a bright green character.
At fixed intervals (50ms), perform these steps:
-
Loop through all columns,
- Check if the current column has more than 12 characters:
- If yes, set its class to
hidden
. The hidden class has a CSS transition effect that reduces its visibility over 1.3 seconds. - Otherwise, do nothing,
- If yes, set its class to
- Check if the current column exceeds about 90% of the page’s height (calculated by the window height and the number of rows in the current div):
- If yes, replace that div with an empty one. By this point, the div’s class has been
hidden
, its visibility has been reduced for a while, so the removal isn’t too abrupt. - Otherwise, do nothing.
- If yes, replace that div with an empty one. By this point, the div’s class has been
And that’s it: the main mechanism involves manipulating the DOM at specific (random) intervals using the setInterval()
method.