Matrix Code Rain

I’ve always wanted to create this: Matrix code rain in Javascript.

Here’s the basic idea behind the animation:

  1. Create empty columns on the page,
  2. Continuously add a random character to a randomly chosen column,
  3. Replace columns that extend beyond the screen with new empty ones.

screenshot

# 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,
  • 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.

And that’s it: the main mechanism involves manipulating the DOM at specific (random) intervals using the setInterval() method.

Written on December 3, 2016

If you notice anything wrong with this post (factual error, rude tone, bad grammar, typo, etc.), and you feel like giving feedback, please do so by contacting me at samubalogh@gmail.com. Thank you!