Skip to content

Instantly share code, notes, and snippets.

@danielt69
Last active April 2, 2020 11:01
Show Gist options
  • Save danielt69/6dca40d79b3c86fa9529c26a00510708 to your computer and use it in GitHub Desktop.
Save danielt69/6dca40d79b3c86fa9529c26a00510708 to your computer and use it in GitHub Desktop.
Matrix rain animation using HTML5 canvas and javascript
// https://codepen.io/P3R0/pen/MwgoKv
var matrix = (function(){
var init = function() {
document.body.style.background = 'black';
var mdr = document.createElement('canvas');
mdr.id = "mdr";
mdr.style.display = 'block';
mdr.style.position = 'fixed';
mdr.style.top = '0';
mdr.style.left = '0';
document.body.prepend(mdr);
var ctx = mdr.getContext("2d");
//making the canvas full screen
mdr.height = window.innerHeight;
mdr.width = window.innerWidth;
//chinese characters - taken from the unicode charset
var chinese = "0123456789abcdefghijlmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ田由甲申甴电甶男甸甹町画甼甽甾甿畀畁畂畃畄畅畆畇畈畉畊畋界畍畎畏畐畑";
//converting the string into an array of single characters
chinese = chinese.split("");
var font_size = 10;
var columns = mdr.width/font_size; //number of columns for the rain
//an array of drops - one per column
var drops = [];
//x below is the x coordinate
//1 = y co-ordinate of the drop(same for every drop initially)
for(var x = 0; x < columns; x++) {
drops[x] = 200; ;
}
window.addEventListener('resize', function(){
window.requestAnimationFrame(function(){
mdr.height = window.innerHeight;
mdr.width = window.innerWidth;
columns = mdr.width/font_size;
for(var x = 0; x < columns; x++) {
drops[x] = 200;
}
});
});
//drawing the characters
var draw = function () {
//Black BG for the canvas
//translucent BG to show trail
ctx.fillStyle = "rgba(0, 0, 0, 0.03)";
ctx.fillRect(0, 0, mdr.width, mdr.height);
ctx.fillStyle = "#00f"; //text color
ctx.font = font_size + "px arial";
//looping over drops
for(var i = 0; i < drops.length; i++) {
//a random chinese character to print
var text = chinese[Math.floor(Math.random()*chinese.length)];
//x = i*font_size, y = value of drops[i]*font_size
ctx.fillText(text, i*font_size, drops[i]*font_size);
//sending the drop back to the top randomly after it has crossed the screen
//adding a randomness to the reset to make the drops scattered on the Y axis
if(drops[i]*font_size > mdr.height && Math.random() > 0.975) {
//if(Math.random() > 0.975) {
drops[i] = 0;
}
//incrementing Y coordinate
drops[i]++;
}
};
setInterval(function(){window.requestAnimationFrame(draw)}, 33);
};
return {
"init":init
};
})();
// init on dom ready
(function(fn){var d=document;(d.readyState=='loading')?d.addEventListener('DOMContentLoaded',fn):fn();})(function(){
matrix.init();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment