黑客帝国纯js版
明天就回家过年了,今天没什么心思上班,看了下博客,发现一个黑客帝国额js版本,地址:https://blog.csdn.net/zhongyi_yang/article/details/53841805
然后做了一点封装,这里也贴出来分享一下:
<!DOCTYPE html> <html> <head lang="zh-cn"> <meta http-equiv=Content-Type content="text/html; charset=utf-8"> <title>简单的黑客帝国效果</title> </head> <body style="height:2000px"> <script type="text/javascript"> (function (window) { var hackerCache = {}; //默认配置 function makeCfg(cfg) { cfg = cfg || {}; var _cfg = { canvas: "hacker_matrix" + ((Math.random() * 10000) >> 0), height: window.innerHeight, width: window.innerWidth, fontSize: 16, fontColor: "#0F0", fontSyle: "16px arial", seeds: "0123456789abcdefghijklmnopqrstuvwxyz", fillStyle: 'rgba(0, 0, 0, 0.05)',//这里只能是rgba格式,好像用ctx.globalAlpha也能做透明度 breaks: 0.98 }; for (var key in _cfg) { _cfg[key] = cfg[key] || _cfg[key]; } return _cfg; } function hacker(cfg) { cfg = makeCfg(cfg); var canvas = document.getElementById(cfg.canvas); //高度及初始化 var altitudes = [], ctx, texts = cfg.seeds.split(''); if (!canvas) { canvas = document.createElement("canvas"); canvas.id = cfg.canvas; canvas.height = cfg.height; canvas.width = cfg.width; document.body.appendChild(canvas); } var cache = hackerCache[canvas.id]; if (!cache) { ctx = canvas.getContext('2d'); var columns = canvas.width / cfg.fontSize; for (var i = 0; i < columns; i++) { altitudes[i] = 1; } hackerCache[canvas.id] = { context: ctx, altitudes: altitudes, interval: undefined } cache = hackerCache[canvas.id]; } altitudes = cache.altitudes; ctx = cache.context; //逐行输出 function drawLine() { ctx.fillStyle = cfg.fillStyle; ctx.fillRect(0, 0, canvas.width, canvas.height); //文字颜色 ctx.fillStyle = cfg.fontColor; ctx.font = cfg.fontSyle; for (var i = 0; i < altitudes.length; i++) { var altitude = altitudes[i]; var y = altitude * cfg.fontSize; var text = texts[Math.floor(Math.random() * texts.length)]; ctx.fillText(text, i * cfg.fontSize, y); if (y > canvas.height && Math.random() > cfg.breaks) { altitude = 0; } altitudes[i] = ++altitude; } } this.start = function () { if (cache.interval === undefined) { cache.interval = setInterval(function () { drawLine(); }, 33); } }; this.stop = function () { cache.interval = cache.interval && clearInterval(cache.interval); } } window.hacker = hacker; })(window); window.onload = function () { //new hacker().start(); new hacker({ canvas: "canvas1" }).start(); new hacker({ canvas: "canvas2" }).start(); new hacker({ canvas: "canvas3" }).start(); new hacker({ canvas: "canvas4" }).start(); } </script> <canvas id="canvas1" width="400" height="400"></canvas> <canvas id="canvas2" width="400" height="400"></canvas> <canvas id="canvas3" width="400" height="400"></canvas> <canvas id="canvas4" width="400" height="400"></canvas> </body> </html>
一个专注于.NetCore的技术小白