Designing visual representations using the Canvas elementorGenerating graphic content

I want to design a creative text image where multiple characters come together to form a word, like "The Matrix", within an animated canvas with a matrix effect. The challenge I'm facing is figuring out how to display the text inside the canvas and then animate it in a way that either blinks or cascades to form the complete word. Below is the code for the canvas setup without the text image:


            var c = document.getElementById("c"),
                ctx = c.getContext("2d");
            c.height = window.innerHeight, c.width = window.innerWidth;
            var matrix = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789@#$%^&*()*&^%+-/~{[|`]}";
            matrix = matrix.split("");
            for (var font_size = 10, columns = c.width / font_size, drops = [], x = 0; x < columns; x++) drops[x] = 1;

            function draw() {
                ctx.fillStyle = "rgba(0, 0, 0, 0.08)";
                ctx.fillRect(0, 0, c.width, c.height);
                ctx.fillStyle = "#0f0";
                ctx.font = font_size + "px courier";
                for (var t = 0; t < drops.length; t++) {
                    var i = matrix[Math.floor(Math.random() * matrix.length)];
                    ctx.fillText(i, t * font_size, drops[t] * font_size);
                    if (drops[t] * font_size > c.height && Math.random() > .975) {
                        drops[t] = 0;
                    }
                    drops[t]++;
                }
            }
            setInterval(draw, 15);
        
<div class="width:50%;height:25vh;background:#000;position:relative;">
          <canvas id="c" style="width:90%;height:75%;position:absolute;z-index:0;"></canvas>
        </div>

Answer №1

I believe I've found a unique solution to your issue. It involves displaying the word "The matrix," but with a 7.5% chance of another character appearing, creating a blinking effect that decrypts the text. It's quite interesting!

To customize this effect, you can designate the word to be written using the variable textToWrite, located just above the drawText() function. This function iterates through each character of textToWrite and calls the generateChar function. In this function, the same character is usually returned, but occasionally a random character is generated instead.

In the drawText function, the returned character is added to the text variable, which is then displayed on the <canvas>.

Feel free to adjust the variables as desired to control the level of 'blinkability.'

var c = document.getElementById("c"),
  ctx = c.getContext("2d");
c.height = window.innerHeight, c.width = window.innerWidth;
var matrix = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789@#$%^&*()*&^%+-/~{[|`]}";
matrix = matrix.split("");
for (var font_size = 10, columns = c.width / font_size, drops = [], x = 0; x < columns; x++) drops[x] = 1;

function draw() {
  ctx.fillStyle = "rgba(0, 0, 0, 0.08)", ctx.fillRect(0, 0, c.width, c.height), ctx.fillStyle = "#0f0", ctx.font = font_size + "px courier";
  for (var t = 0; t < drops.length; t++) {
    var i = matrix[Math.floor(Math.random() * matrix.length)];
    ctx.fillText(i, t * font_size, drops[t] * font_size), drops[t] * font_size > c.height && Math.random() > .975 && (drops[t] = 0), drops[t]++
  }
}

let textToWrite = "The Matrix";

function drawText() {
  let textArr = textToWrite.split("");
  var text = '';
  for (var i = 0; i < textToWrite.length; i++) {
    text += generateChar(textArr[i]);
  }

  ctx.font = "60px courier";
  ctx.fillStyle = "#0f0";
  ctx.textAlign = "center";
  ctx.fillText(text, c.width / 2, c.height / 2);
}

function generateChar(char, pos) {
  if (Math.random() > 0.075) {
    return char;
  } else {
    return matrix[(Math.floor(Math.random() * matrix.length))];
  }
}
setInterval(draw, 15);
setInterval(drawText, 30);
<div class="width:50%;height:25vh;background:#000;position:relative;">
  <canvas id="c" style="width:90%;height:75%;position:absolute;z-index:0;"></canvas>
</div>

Hopefully, this contributes positively! If not, feel free to share any feedback.

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

Tips for choosing between options in JavaScript and AngularJS

How can I choose the appropriate <select> tag option using JavaScript or AngularJS in the backend? Hint: I receive data from an API service and populate a form for editing. Assuming the gender is currently set as Male in the database, how can I disp ...

Issue with window resize directive not functioning as expected

I have recently crafted a personalized directive in AngularJS. Here's the code snippet: var esscom = angular.module('esscom',['ngMaterial' ,'ngMessages','ui.bootstrap','ui.router']); esscom.directiv ...

Is there a way to add additional text to a text element within an SVG?

Is it possible to append a new text element at the end of the data label by clicking on that particular text? I have attempted to implement this in my code but the additional text is not being displayed as expected: circleGroup.selectAll("text") ...

The pop-up menu appears in a location different from where the anchor element is positioned

Having an issue with the menu placement when clicking on an Avatar. The menu is appearing in the wrong position: https://i.sstatic.net/955eJ.png The avatar button "OB" on the right side is where the issue occurs. No console errors present and inspecting ...

Load HTML 5 video on a webpage after all other elements have finished loading

Hello there! I'm trying to figure out a way to load an HTML 5 video after the page has already loaded. Currently, the video pauses all site interaction until it's fully loaded, but I'd prefer to have it display an image first and then autopl ...

The array does not seem to be properly linked in React JS

I've been encountering this error even after trying various solutions based on my knowledge. Any help would be greatly appreciated. The issue arises when I attempt to pass an array in props, retrieve it in the component, and then set the props value ...

The timeline shows the movement of the jQuery object

I currently have a timeline bar that looks like this: <div class="plan-bar main-gradient"></div> https://i.stack.imgur.com/ybJar.jpg My question is, how can I make the red box move in real-time along this timeline bar? Thank you for your hel ...

Updating form values when a radio button is changed using asynchronous JavaScript and XML (AJ

Here is the form I have created: <form method="post" action="options.php" id="pay_what_you_want_form"> <input type="radio" name="payment_period" value="monthly" id="monthly" checked><label for="monthly" class="payment_period_label"> ...

How can you effectively use a table filter extension to sort through dropdown values?

Is there a way to update the dropdown values based on new data after applying the first filter? For example, only displaying $0 in the second dropdown menu? Essentially, I want to filter the values in a table and then have the dropdown options reflect the ...

Having trouble with NextAuth's Google provider on Safari?

I've encountered an issue where the Google provider works perfectly on Chrome and other browsers, but fails to work on Safari. Despite going through the documentation thoroughly, I couldn't find any relevant information to resolve this. This is ...

I am looking to dynamically add values into a hash map

var markerList1={}; var markerList=[]; and incorporating iterator values from a single for loop function addSomething() // this function will run multiple times from a for loop { image ='../css/abc/'+image[iterator]+'.png&apos ...

Unable to center div container with margin set to auto

I'm struggling to center my container on the website. My goal is to have it centered and take up about 80% of the page so I can incorporate an image slider and text inside. Using margin: 0 auto doesn't seem to be achieving what I want. The backgr ...

jPlayer 2.0 Time Tracker: Know How Much Time Has Passed and How Much

Using jPlayer 2.0 for my project. The play, pause, and other functions are all working fine, but I'm struggling to retrieve the elapsed/remaining time attributes from the jquery object. I've experimented with event handlers and tried setting up ...

Using a jQuery script, you can enable a back button functionality that allows users

I created a survey to assist individuals in determining where to go based on the type of ticket they have. However, I am currently facing difficulties with implementing a "Back" button that will display the previous screen or "ul" that the user saw. Initia ...

Dynamic row height in MUI DataGrid

I'm currently utilizing the MUI DataGrid component, and I have a specific behavior in mind that I'd like to achieve: When there is a small number of rows present, I want the table to only occupy the necessary space for those rows. On the other h ...

The pages are constantly showing an error message that reads, "There is a problem with the SQL syntax in your code."

I am having trouble with my login page as it is displaying an error on my index.php file. Below is the code snippet from my index.php: <?php include('supsrwk_epenyenggaraan.php'); ?> <?php if (!function_exists("GetSQLValueString")) { f ...

What is the best way to retrieve an array of other models from a parent model in Mongoose using queries?

Two Schema exist for user and todo. Each todo is associated with an owner who is a user, and each user has an array of todos. // user.js const TodoSchema = require('./todo').TodoSchema; var UserSchema = mongoose.Schema({ name: { type: String, ...

Limit not reached by substring function

When the character limit exceeds 20 characters, the substring function extracts the first 20 characters typed in the input. It replaces any additional characters that are entered after reaching the max limit of 20. In my program, however, I am able to con ...

Is there a way to compare the elements of an array with those of another array containing nested arrays in order to identify matching results?

Every user in our database has specific skills assigned to them. We maintain a list of available skills with unique IDs. The objective is to filter users based on the skill we are interested in, like displaying all Janitors. We are utilizing Vue.js and im ...

What steps should be taken to resolve the error message "This Expression is not constructable"?

I'm trying to import a JavaScript class into TypeScript, but I keep getting the error message This expression is not constructable.. The TypeScript compiler also indicates that A does not have a constructor signature. Can anyone help me figure out how ...