Transforming your website with a dynamic background: Implementing a Javascript raining matrix code effect

I've run into a problem where I'm struggling to overlay text, an image, and a video on a JavaScript script. I've searched on YouTube and Google for answers, but haven't found any solutions yet. Can anyone help me out? Thanks!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./styles.css">
    <title></title>
</head>
<body style="background-color: black">
  

    <canvas id="Matrix" style="width: 100%; height: 100%;"></canvas>
    <script src="./index.js"></script>

  


</body>
</html>
html {
    background: black;
    height: 100%;
    overflow: hidden;
}

body {
    margin: 0;
    padding: 0;
    height: 100%;
}
const canvas = document.getElementById('Matrix');
const context = canvas.getContext('2d');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

const katakana = 'アァカサタナハマヤャラワガザダバパイィキシチニヒミリヰギジヂビピウゥクスツヌフムユュルグズブヅプエェケセテネヘメレヱゲゼデベペオォコソトノホモヨョロヲゴゾドボポヴッン';
const latin = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const nums = '0123456789';

const alphabet = katakana + latin + nums;

const fontSize = 16;
const columns = canvas.width/fontSize;

const rainDrops = [];

for( let x = 0; x < columns; x++ ) {
    rainDrops[x] = 1;
}

const draw = () => {
    context.fillStyle = 'rgba(0, 0, 0, 0.05)';
    context.fillRect(0, 0, canvas.width, canvas.height);
    
    context.fillStyle = '#0F0';
    context.font=`fontSize + 'px monospace`;

    for(let i = 0; i < rainDrops.length; i++)
    {
        const text = alphabet.charAt(Math.floor(Math.random() * alphabet.length));
        context.fillText(text, i*fontSize, rainDrops[i]*fontSize);
        
        if(rainDrops[i]*fontSize > canvas.height && Math.random() > 0.975){
            rainDrops[i] = 0;
        }
        rainDrops[i]++;
    }
};

setInterval(draw, 30);

I hope to use the JavaScript script as the background of my website while utilizing only HTML, CSS, and JS.

Answer №1

By utilizing this helpful answer, you can implement the use of position: absolute to position elements above the canvas.

const canvas = document.getElementById('Matrix');
const context = canvas.getContext('2d');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

const katakana = 'アァカサタナハマヤャラワガザダバパイィキシチニヒミリヰギジヂビピウゥクスツヌフムユュルグズブヅプエェケセテネヘメレヱゲゼデベペオォコソトノホモヨョロヲゴゾドボポヴッン';
const latin = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const nums = '0123456789';

const alphabet = katakana + latin + nums;

const fontSize = 16;
const columns = canvas.width / fontSize;

const rainDrops = [];

for (let x = 0; x < columns; x++) {
  rainDrops[x] = 1;
}

const draw = () => {
  context.fillStyle = 'rgba(0, 0, 0, 0.05)';
  context.fillRect(0, 0, canvas.width, canvas.height);

  context.fillStyle = '#0F0';
  context.font = fontSize + 'px monospace';

  for (let i = 0; i < rainDrops.length; i++) {
    const text = alphabet.charAt(Math.floor(Math.random() * alphabet.length));
    context.fillText(text, i * fontSize, rainDrops[i] * fontSize);

    if (rainDrops[i] * fontSize > canvas.height && Math.random() > 0.975) {
      rainDrops[i] = 0;
    }
    rainDrops[i]++;
  }
};

setInterval(draw, 30);
html {
  background: black;
  height: 100%;
  overflow: hidden;
}

body {
  margin: 0;
  padding: 0;
  height: 100%;
}


/* Color of the text - you can change it as you need. */

div {
  color: red;
}


/* These are the properties applied to div that has the "innerDiv" class - you can change it as you need. */

.innerDiv {
  position: absolute;
  left: 10px;
  top: 10px;
}
<canvas id="Matrix" style="width: 100%; height: 100%;"></canvas>
<script src="./index.js"></script>
<div id="wrapper">
  <div class="innerDiv">
    <span>This is an title example:</span>
    <br/>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Optimizing React components by efficiently updating props without triggering unnecessary renders

As I delve into learning React, I've encountered a challenge with using a component to display details of a selected item in a table. The issue arises when clicking "Next" on the paginated table, causing the state to update and re-render the component ...

Tips for creating a collapsible side menu that doesn't disrupt the main page

https://i.sstatic.net/ReyZo.png https://i.sstatic.net/DPbVZ.png These images are just from a random website for demonstration purposes. I am trying to create a sidebar that expands without affecting the rest of the page. Any tips on how to achieve this ...

Tips for placing a side navigation button on top of the side navigation bar

Having trouble implementing the open and close button for side navigation along with a search bar above the side navigation, similar to the example shown here. I am utilizing bootstrap 4 as my framework. Feel free to check out the source code on https:// ...

What is the best way to create a function that shifts a musical note up or down by one semitone?

Currently developing a guitar tuning tool and facing some hurdles. Striving to create a function that can take a musical note, an octave, and a direction (up or down), then produce a transposed note by a half step based on the traditional piano layout (i. ...

Use jQuery to retrieve the response from a JSON request and showcase it on the existing HTML page

Currently, I am working on a project that involves integrating a JSON-based web service from a remote server. The method of this service can be accessed by using specially formatted URLs such as: http://root-url/ws/service-name?request={json-string} The ...

Guide on creating a Sequelize query to retrieve all tasks linked to a specific user_id

I'm currently developing my first to-do list application using node express ejs and sequelize with sqlite Below is my sqlite.js file which contains the database schemas: const Sequelize = require("sequelize"); const sequelize = new Sequelize({ dia ...

Is it possible to view the value of a JavaScript local variable without relying on breakpoints in a web browser?

Is there a way to access the values of a local variable in an external script that is called on the page even after making the code start again? I am able to see its values when placing a breakpoint, but they are inaccessible once the code restarts. ...

Transforming an HTML and Javascript Project into a Standalone Application

Currently, I am engaged in a side project to enhance my skills in HTML/CSS/JavaScript. I have been using Aptana as my primary tool for coding, and it is configured to run smoothly in a browser environment. Specifically, the project I am working on is a te ...

Personalized PHP Error Handler incorporating Notification

I am seeking a way to display PHP error information in a JavaScript alert box. I have attempted to utilize PHP's set_error_handler(), but I am encountering issues where it only displays the default error and prevents me from choosing other options. s ...

Tips for making sure AngularJS runs a function and its subfunction sequentially

How do I run the code below to display the details of each flavor and its corresponding ITEM ID in a specific order. Execution Format: Flavor1, Flavor2 -- Getflavors() Flavor1 ITEM1, ITEM2... -- GetItemIDs_ofeachFlavor(MapFlvID) GET ITEM1 DETAILS and ad ...

Ensure that your JQuery code only runs after Angular has completed its rendering

As a newcomer to Angular JS, I may have a question that seems silly. Despite seeing it discussed in several SO questions, I still couldn't figure it out. My goal seems simple, yet I've had a tough time achieving it. I'm attempting to execut ...

Bring in the Stencil JS library from a separate Stencil JS library

Within my collection of Stencil JS web components, I have two distinct libraries - library-a and library-b. These are not complete applications, but rather separate npm packages containing various components. I am interested in incorporating certain compo ...

The deferred type in Typescript that extends T is unknown at this time

While reviewing code in a library, I came across the line unknown extends CustomTypes[K]. My understanding is that this is a deferred type where unknown can always be assigned to CustomTypes[K]. However, I am unsure how this type is utilized and in what ...

Is there a way to customize the timepicker pop-up so that it extends the entire width of the parent form control

<FormControl fullWidth> <LocalizationProvider dateAdapter={AdapterDayjs}> <TimePicker views={["hours", "minutes", "seconds"]} label={t("StrategyManager.Select_Time")} value={timer} ...

Creating an Angular Js Application that offers two distinct user interfaces

I'm faced with a challenge in my work on a large AngularJS application that consists of multiple modules. The issue is that I now need to integrate a static website into this application, and the website has a completely different layout compared to m ...

Using Node.js and Typescript to implement a chain of logical AND operations with an array of any length

Setting: I am developing a versatile function that determines a boolean outcome based on logical AND operations. However, the function is designed to handle various types of objects and arrays, each requiring different conditions. Currently, my code look ...

The process of converting an object to a string in Typescript

Currently, I am transforming an Object in Typescript into a string for storage in a database. formData.survey_data = encodeURI(JSON.stringify(formData.survey_data)); The result functions correctly in the browser, however, there is an error being flagged ...

Trouble displaying custom markers in VueJS using Google Maps API

I have integrated vue2-google-maps to display a map and add markers on specific locations. Here is the code snippet showing the map components along with the props passed to it. <gmap-map id="map" :center="center" :zoom="5" ...

Leveraging Json data in Angular components through parsing

I am currently developing an angular application where I need to retrieve and process data from JSON in two different steps. To start, I have a JSON structure that is alphabetically sorted as follows: { "1": "Andy", "2": &qu ...

An easy way to ensure IE opens PDF links in an iframe in a new tab

I've encountered an issue while trying to display pdf files on an html page using an iframe. Here's my code snippet: <iframe src="testfile.pdf" width="100%" height="100%"></iframe> My problem is that the links within the pdf always ...