Wave-Pattern Matrix Rain Animation With HTML, CSS, and JavaScript

by nasaleader in Circuits > Computers

394 Views, 5 Favorites, 0 Comments

Wave-Pattern Matrix Rain Animation With HTML, CSS, and JavaScript

Screenshot 2024-09-24 210719.png

Introduction

In this project, we will create a visually stunning Wave-Pattern Matrix Rain Animation using HTML, CSS, and JavaScript. Inspired by the classic Matrix code rain effect, this project will enhance the original effect with wave-like motion and multi-colored falling characters. This animation will run on a full-screen HTML canvas and provide a mesmerizing wave effect where each letter dances down the screen with varying colors and undulating motion.

The main goal is to combine mathematical wave functions with a classic text animation, producing a fluid, visually engaging experience. Whether you're looking to add some flair to your website or simply exploring the fun of creative coding, this project offers a perfect blend of design and code!

Supplies

Screenshot 2024-09-24 210442.png
Screenshot 2024-09-24 210514.png
Screenshot 2024-09-24 210549.png
Screenshot 2024-09-24 210618.png
Screenshot 2024-09-24 210719.png

Supplies

To build this project, you will need the following:

  1. Text Editor:
  2. We will be coding in HTML, CSS, and JavaScript, so you need a code editor like Visual Studio Code, Sublime Text, or Atom. Visual Studio Code is a popular choice due to its powerful features and user-friendly interface.
  3. HTML File (index.html):
  4. This will define the structure of the page, where we’ll set up the <canvas> element.
  5. CSS File (styles.css):
  6. Used for minimal styling and ensuring the canvas fits the screen and removes default browser padding/margin.
  7. JavaScript File (main.js):
  8. This file contains the core logic for the Matrix wave animation, handling the characters’ motion, the wave effect, and the random color generation.
  9. A Modern Browser:
  10. Any browser that supports HTML5 canvas and JavaScript (e.g., Chrome, Firefox, or Edge) will work to display the animation.

With these supplies ready, you're all set to create a dynamic, wave-based Matrix rain effect.

This project makes the letters look like they are "surfing" down the screen in a wave pattern. The key differences are:

  1. Wave Motion: Letters fall in a sine wave pattern, making the fall more dynamic.
  2. Multiple Colors: Letters change colors as they fall to give a gradient or rainbow effect.

1. HTML Code (Main.html)

2. CSS Code (Command.css)

3. JavaScript Code (Main.js)

Explanation of Key Changes:

  1. Wave Motion: The sine function creates a wave-like effect for each column. The wave's height (waveAmplitude) and frequency (waveFrequency) control the appearance.
  2. Color Variation: Each letter is randomly assigned a color from a palette. You can modify the colors in the colors array to change the effect.
  3. Wave Offset: As the waveOffset increases, the wave moves across the screen, making it look dynamic as letters fall in sync with the wave.

Preview:

This effect will make the letters fall down in a wave-like motion, with the letters changing color as they move. You can experiment with wave parameters to control how dramatic the wave is, and tweak the color scheme to your preference.

Step 1: Create the HTML File

  1. Open Visual Studio Code.
  2. Create a new file and name it main.html.
  3. Add the following HTML code:
  4. This file sets up the structure of the webpage and links the CSS and JavaScript files.
  5. It also defines the <canvas> element where the animation will be drawn.

Step 2: Create the CSS File

  1. Create another file and name it command.css.
  2. Add this CSS code to style the canvas:
  3. This CSS ensures the canvas takes up the full screen with no margins or padding. The background is black to match the classic Matrix aesthetic.

Screenshot 2024-09-24 210549.png
Screenshot 2024-09-24 210618.png

Step 3: Create the JavaScript File

  1. Create a third file and name it main.js.
  2. Add the following JavaScript code:
  3. This code handles the animation of the letters, making them fall in a wave-like pattern while changing colors.
  4. It defines the letters, the wave motion, the color transitions, and the loop that keeps the animation running.


Screenshot 2024-09-24 210719.png

Step 4: Test the Code

  1. Save all three files (main.html, command.css, and main.js).
  2. Open main.html in a browser. You should now see the letters falling in a wave pattern across the screen, with random colors!

Explanation of each line

Canvas and Context Setup

// Get canvas and set up context
const canvas = document.getElementById("matrixCanvas");
const ctx = canvas.getContext("2d");
  1. const canvas = document.getElementById("matrixCanvas");: This selects the <canvas> element from the HTML using its ID (matrixCanvas). This is where all the drawing and animation will occur.
  2. const ctx = canvas.getContext("2d");: We create a 2D context for drawing on the canvas. The ctx variable allows us to use 2D drawing functions like drawing shapes, text, etc.

Set Canvas Size

// Set canvas size
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
  1. canvas.width = window.innerWidth;: This sets the width of the canvas to match the width of the browser window (making it responsive).
  2. canvas.height = window.innerHeight;: This sets the height of the canvas to match the height of the browser window.

Define Letters

// Define the letters that will fall
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#$%&*".split("");
  1. This defines a string of all the characters that will be used in the falling animation.
  2. .split(""): This splits the string into an array of individual characters. Each character is now accessible by its index, making it easy to select random letters for the animation.

Set Font Size and Calculate Columns

// Font size and columns
const fontSize = 16;
const columns = canvas.width / fontSize;
  1. const fontSize = 16;: This sets the size of the falling characters to 16 pixels.
  2. const columns = canvas.width / fontSize;: We calculate how many vertical columns can fit across the canvas. It’s calculated by dividing the canvas width by the font size. Each column will be 16 pixels wide, and characters will fall down each of these columns.

Initialize Drops Array

// Initialize an array to store the vertical position of drops
let drops = Array.from({ length: columns }, () => 1);
  1. Array.from({ length: columns }, () => 1);: We create an array called drops with a length equal to the number of columns.
  2. Each element in this array represents the current vertical position of a letter in a particular column.
  3. Initially, all letters start at position 1 (top of the screen).

Color Palette

// Color palette for the gradient effect
const colors = ["#0f0", "#00f", "#f00", "#ff0", "#0ff", "#f0f", "#fff"];
  1. This defines an array of color codes. Each falling letter will randomly pick one of these colors to display.
  2. "#0f0" is green (the classic Matrix color).
  3. You can modify these hex color codes to customize the color scheme.

Wave Parameters

// Wave parameters
const waveAmplitude = 50; // Height of the wave
const waveFrequency = 0.05; // Frequency of the wave
let waveOffset = 0; // This will move the wave
  1. waveAmplitude = 50;: This controls the height of the wave motion. A larger value will create taller waves.
  2. waveFrequency = 0.05;: This determines the spacing between wave peaks. A smaller value creates more stretched-out waves, while a larger value creates tighter waves.
  3. waveOffset = 0;: This will be incremented in the animation loop to move the wave across the screen over time.

Draw Function

// Draw function
function draw() {
  1. This defines the draw() function, which contains all the logic to render each frame of the animation. This function will be called continuously to keep the animation running.

Clear the Canvas with a Semi-Transparent Fill

// Fill the background with a semi-transparent black color to create trails
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
  1. ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';: This sets the fill color to a semi-transparent black. The 0.1 opacity allows the previous frame to partially show through, creating the motion trail effect.
  2. ctx.fillRect(0, 0, canvas.width, canvas.height);: This fills the entire canvas with the semi-transparent black color, “erasing” the previous frame but leaving a faint trail.

Loop Through Each Column

// Loop through each column
for (let i = 0; i < drops.length; i++) {
  1. This loop goes through each column, where i represents the column index. Each column will display one falling letter.

Calculate Wave Offset for Each Column

// Calculate the wave offset using sine function
let wave = Math.sin(i * waveFrequency + waveOffset) * waveAmplitude;
  1. Math.sin(i * waveFrequency + waveOffset): This generates a sine wave for the column. The waveFrequency controls how tightly packed the waves are, and waveOffset shifts the wave horizontally as the animation progresses.
  2. * waveAmplitude: This scales the height of the wave. The wave height is multiplied by waveAmplitude to control how high or low the letters move in a wave pattern.

Pick a Random Letter and Color

// Pick a random letter and random color for each drop
let letter = letters[Math.floor(Math.random() * letters.length)];
let color = colors[Math.floor(Math.random() * colors.length)];
  1. letters[Math.floor(Math.random() * letters.length)]: This picks a random letter from the letters array by generating a random index.
  2. colors[Math.floor(Math.random() * colors.length)]: This selects a random color from the colors array to apply to the letter.

Draw the Letter on the Canvas

// Set the letter color and draw it at its current position, including wave offset
ctx.fillStyle = color;
ctx.font = `${fontSize}px monospace`;
ctx.fillText(letter, i * fontSize, drops[i] * fontSize + wave);
  1. ctx.fillStyle = color;: Sets the color of the letter to the randomly chosen color.
  2. ctx.font = ${fontSize}px monospace;: Sets the font size and style. The monospace font ensures each letter takes up the same amount of space.
  3. ctx.fillText(letter, i * fontSize, drops[i] * fontSize + wave);: This draws the letter on the canvas at the correct position:
  4. i * fontSize: The horizontal position is determined by the column number (i), each column being fontSize pixels wide.
  5. drops[i] * fontSize + wave: The vertical position is determined by the current drop’s vertical position (drops[i]) plus the wave offset.

Move Drops Down the Screen

// Move the drop down, reset if it reaches the bottom
drops[i]++;
if (drops[i] * fontSize > canvas.height || Math.random() > 0.975) {
drops[i] = 0; // Reset the drop to the top with some randomness
}
  1. drops[i]++: This moves the letter down by increasing its vertical position (drops[i]).
  2. if (drops[i] * fontSize > canvas.height || Math.random() > 0.975): This checks if the letter has reached the bottom of the screen. If so, or if a random chance occurs (Math.random() > 0.975), the letter will be reset to the top of the screen.
  3. drops[i] = 0;: Resets the letter's vertical position back to the top of the canvas, creating a continuous falling effect.

Move the Wave

// Move the wave
waveOffset += 0.1;
  1. waveOffset += 0.1;: This increases the waveOffset slightly on each frame, which makes the wave move horizontally over time.

Keep Drawing the Animation

// Keep drawing the animation
requestAnimationFrame(draw);
}
  1. requestAnimationFrame(draw);: This is the function that continuously calls the draw function, creating the smooth animation. It tells the browser to call draw at the next available screen repaint.

Start the Animation

// Start the animation
draw();
  1. This calls the draw() function for the first time, starting the loop that will continuously update the canvas and animate the falling letters.