What is the best way to superimpose an image onto a canvas?

I am working on a cool project where I have created a canvas that displays matrix binary code raining down. However, I would like to enhance it by adding an image overlay on top of the canvas.

Here is my current setup:

<div class="rain">
            <canvas id="Matrix"></canvas>
             <div class ="imgclass">
                <img class="imgclass" src="assets/image.jpg"/>
            </div>
        </div>

This is the JavaScript code responsible for the animation on the canvas:

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

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const latin = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const nums = '0123456789';

const alphabet = 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);

and here's the CSS styling:

.rain {
    background: black;
    height: 40%;
    overflow: hidden;
}

canvas {
    background-image: url("assets/img.jpg");
}

The issue I am facing is that the image does not appear on the canvas as intended, instead, it displays below the canvas. I'm looking for a solution to position the image in the middle of the canvas.

Answer №1

To create a CRT effect on your canvas, simply wrap the canvas in a div element and apply the necessary CSS properties to mimic the desired effect.

Below is an example of how you can achieve a Matrix-style animation on your canvas:

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

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const latin = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const nums = '0123456789';

const alphabet = 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);
@keyframes flicker {
  50% {
    top: -3px;
  }
}

.crt::before {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  content: "";
  display: block;
  background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAGCAYAAADkOT91AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAqSURBVBhXYxTiF68WZ2TQeqLE8o3hicEbJgY0gFNgHRBvBuK9hLQwMAAAF54HHx1Goh0AAAAASUVORK5CYII=");
  background-size: 4px, 6px;
  opacity: 0.9;
  background-repeat: repeat;
  image-rendering: optimizeSpeed;
  pointer-events: none;
  filter: contrast(50%);
  animation: flicker 0.08s step-end infinite;
}

html,
body {
  margin: 0;
  padding: 0;
  overflow: hidden;
}
<div class="crt">
  <canvas id="Matrix"></canvas>
</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

Relocating sprite graphic to designated location

I am currently immersed in creating a captivating fish animation. My fish sprite is dynamically moving around the canvas, adding a sense of life to the scene. However, my next goal is to introduce food items for the fishes to feast on within the canvas. Un ...

Guide on showcasing the values from two text fields with autocomplete suggestions in a third text field

Hey there, I have a search form that takes values from two text fields and combines them to populate a third text field for querying. <form name="form1" method="post" action="" autocomplete="off" oninput="sea.value = password.value +''+ passw ...

How to choose a particular Excel spreadsheet in Angular before importing the file?

I am currently working on a new feature that allows users to choose a specific Excel worksheet from a dropdown list before importing a file. However, I am facing some difficulty in adding the worksheet names to the dropdown list. Right now, I have placehol ...

The navigation bar in Bootstrap 3.2 expands in size as you scroll past it

Whenever I reach the bottom of the page, the navigation bar suddenly enlarges. The navbar is located at the top of my code. I attempted moving the navigation to the bottom of the code... but it didn't fix the issue... Could someone please identify wha ...

Nuxt 2.5 and higher do not recognize the definition of Global

After utilizing Nuxt 2.1 in my app, I proceeded to upgrade it gradually and everything was fine until Nuxt 2.4. However, starting from version 2.5 and above, production builds are breaking with an error stating global is not defined. The location of the e ...

Having trouble getting the expected transition effects to work with Vue.js

Currently, I have a display of lists of items through the use of v-for. Initially, only the summary section of each item is visible. Upon clicking on an item, the details section is supposed to appear. This functionality is achieved by adding or removing ...

Main navigation category as parent and secondary category as a child menu in WordPress

Hello there, I am looking to create a navigation menu with parent categories displayed horizontally and child categories as corresponding submenus. For example, The parent categories would be Apple, Orange, and Mango Under Apple, we would have apple1, ...

Updating of an Angular Directive within a nested Directive ceases once the inner Directive has been modified

Encountered a challenge with directives nested within each other in AngularJS. The issue is that both directives share the same property through a service and have an input to modify this property. The outer directive uses "transclude" to include the inner ...

Customizing skin CSS for DNN Portal and Page images

Currently, I have a unique custom skin that I personally created. It is implemented on multiple portals that I am responsible for managing. My goal is to incorporate the ability for the header image to change based on the specific page being viewed. The he ...

Adjusting the decimal points of numbers within a table to create the illusion of a "centered" alignment within the cell

Looking for a table design featuring a column of decimal numbers, each with varying lengths before and after the decimal point, while keeping the decimal points aligned. The width of the column should be flexible, expanding to accommodate long numbers in ...

Issues with displaying HTML5 audio player in iOS Chrome and Safari browsers

My html5/jquery/php audio player is working well on desktop browsers, but when I tried testing it on iOS, all I could see was a grey track bar. I suspect that the controls are hidden behind the track bar because sometimes the associated file starts playing ...

Uncover the content of a base64 encoded string and convert it into

A JSON response has been linked on the user's request to retrieve an excel document. The structure of the response is as follows: { "format": // file extn ----only xls "docTitle": //file name "document" :// base 64 encoded data } The attem ...

Stop horizontal overflow of content

This unique Vuetify demo on CodePen showcases a two-column layout. The first column contains a <v-list> enclosed in a green <v-alert>. By clicking the "toggle text" button, you can switch the title of the first list item between short and long ...

Loop through the ng-content elements and enclose each one within its own individual nested div

Although it is currently not supported, I am curious to know if anyone has discovered a clever solution to this problem. In my current setup, I have a parent component with the following template: <dxi-item location='after' class="osii-item- ...

Building basic objects in TypeScript

My current project involves utilizing an interface for vehicles. export interface Vehicle { IdNumber: number; isNew: boolean; contact: { firstName: string; lastName: string; cellPhoneNumber: number; ...

Is Firebug a necessary tool for the functioning of my website?

I'm currently tackling a new project that involves complex javascript development. Unfortunately, I am unable to share any code specifics at this time. Initially, my script functioned correctly in Firefox 3.0 but encountered issues when tested on Fir ...

Trouble Viewing Image File

I am facing an issue where I cannot upload an image file from my computer onto my HTML file, as it is not showing up in the browser. However, when I link an image file from the web, it works perfectly fine. I have double-checked the file path and ensured ...

"Obtaining header requests in node.js: A step-by-step guide

Currently, as I work on developing the elasticsearch API application, my task involves retrieving the header request from an AJAX call on the server side. The AJAX request is as follows: $.ajax({ url: 'http://localhost:3002/api/v1/getAutoSu ...

Conceal the overflow from absolutely positioned elements

I've gone through all the similar examples but still struggling to find the correct solution. My issue involves a basic Side Menu that toggles upon button click. Within the menu, there is a list of checkboxes positioned absolutely with the parent con ...

Is there a more efficient method for iterating through this object?

Working with JSON and JS var data = { "countries": { "europe" : [{name: "England", abbr: "en"}, {name: "Spain", abbr: "es"}], "americas" : [{name: "United States"}], "asia" : [{name: "China"}] } }; JavaScript Loop for (k in data) { fo ...