Cool HTML5 matrix effect

  sonic0002        2013-08-14 08:03:34       30,693        2    

Do you still remember the movie The Matrix? Do you still remember the cool matrix effect in that movie? How is that effect achieved? Shaun Dunne shared a piece of HTML5 code which displays a cool matrix effect. The matrix demo can be found here.

Below is the code which he achieves this effect: with

var s = window.screen;
var width = q.width = s.width;
var height = q.height = s.height;
var letters = Array(256).join(1).split('');

var draw = function () {
  q.getContext('2d').fillStyle='rgba(0,0,0,.05)';
  q.getContext('2d').fillRect(0,0,width,height);
  q.getContext('2d').fillStyle='#0F0';
  letters.map(function(y_pos, index){
    text = String.fromCharCode(3e4+Math.random()*33);
    x_pos = index * 10;
    q.getContext('2d').fillText(text, x_pos, y_pos);
    letters[index] = (y_pos > 758 + Math.random() * 1e4) ? 0 : y_pos + 10;
  });
};
setInterval(draw, 33);

Let's get to understand this piece of code line by line:

The first 3 lines are easy to understand, line 2 and line 3 will store the width and height of the screen to the variable width and height.

Line 4 will create a 256 elements array where each element in the array is "1".

Line 6 to the second last line is the callback function of the setInterval() function in the last line.

Line 7 and 8 will fill the screen with background color of black and an alpha factor of 0.05. When each time the draw function is called, this will draw the background on the screen. This is why we can see the text has different color at different places. Some text will have green color without transparent background color. This is because there will be a new layer drawn on the screen each time the draw is called

Line 9 will change the fill color to green so that the the text drawn on the screen will be green.

Line 10 call the Array.prototype.map() function, this will apply the callback function on each element of the letters array. The two parameters y_pos and index are the value and index of each element of the array respectively. The initial y_pos is 1 for all elements.

Line 11 will generate a random character to be drawn next

Line 12 will set the x position of each text to be drawn from left to right.

Line 13 will draw the text at respective x and y position.

Line 14 will set the next y position for each element. The y position will be randomly generated so that we can see each element in the array will show at different y positions. This will create the cool matrix effect.

The last line will start to draw the matrix with a time interval of 33 milliseconds.

HTML5  MATRIX 

       

  RELATED


  2 COMMENTS


Cool [Reply]@ 2015-09-02 08:45:51

 

 

 

 

 

cool

Anonymous [Reply]@ 2021-08-29 21:26:03

where should I write ?

and what is the file type ?

 



  RANDOM FUN

Artificial intelligence