JSFiddle - React, Tailwind, and code Playground
by Rahul Sharma
HTML
<canvas id="background" width="512" height="360">
</canvas>
JavaScript
function Bit (){
// x and y positions are randomized
this.xpos = Math.random() * canvas.width;
this.ypos = Math.random() * 2 * canvas.height - canvas.height;
// this draw the text for current frame
this.draw = function(){
// Formatting the text to display
context.fillStyle = 'green';
context.font = '14pt Calibri';
var text = "test";
var textWidth = context.measureText("W.").width;
// we need to draw the characters of the text
// one by one from top to bottom
for(var i=0; i<text.length; i++){
var charaterWidth = context.measureText(text[i]).width;
context.fillText( text[i],
this.xpos - charaterWidth/2,
this.ypos + i*textWidth);
}
};
// this will update the text for next frame
this.tick = function(){
if(this.ypos > canvas.height){
// if text crosses the bottom of the screen then reset
this.ypos = -canvas.height;
this.xpos = Math.random() * canvas.width;
}
else
this.ypos += 2; // drop text by 2 pixels down
};
}
var canvas = document.getElementById('background');
var context = canvas.getContext('2d');
var bits = new Array();
for(var i = 0; i < 50; ++i)
bits.push(new Bit());
function reDraw(){
// before drawing clear entire screen
context.fillStyle = 'black';
context.fillRect(0, 0, canvas.width, canvas.height);
// draw every text elements
for(var bit in bits){
bits[bit].draw();
bits[bit].tick();
}
}
// This will call 'reDraw' at every 33 milliseconds.
// So, our animation will run at 30fps (1000/33 ≈ 30).
setInterval(reDraw, 33);