Matrix Code Rain

This is something that I wanted to do for a long time: Matrix code rain in Javascript.

The basic concept of the animation is the following:

  1. Form empty columns on the page,
  2. add a random character to a randomly selected column; repeat,
  3. replace columns that are too long to fit on the screen with empty ones.

screenshot

# Setup

  • Declare our character set: half-width kana’s and lowercase ascii letters:

    。「」、・ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙゚, 0123456789abcdefghijklmnopqrstuvwxyz

  • define a function that returns a random value up to its argument (it will be used for generating random characters, selecting random columns and getting random intervals as well).

# Forming columns

  • calculate the number of columns that fit onto the screen (to have some responsiveness),
  • add the calulated number of <div></div> elements to the page.

# Doing the heavy lifting

At varying random intervals, do the following steps:

  • select a random column, append a span element with class='new',
  • append a random character to the new span,
  • after 130 ms, set the span’s class to old.

The new class represents a newly created character, white in color. The old class is a bright green character.

At fixed intervals (50ms), do the following 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 in 1.3 seconds.
    • otherwise, do nothing,
  • check if the current column has more than around 90% of the page’s height (this is calculated by getting the window height and the number of rows so far in the current div):
    • if yes, replace that div with an empty one. At this point we are sure that the div’s class has been hidden, its visibility has been decreased for some time, so the removal is not too sudden to the eye.
    • otherwise, do nothing.

That’s it: the main mechanism is done by manipulating the DOM at certain (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!