JS+CSS+HTML实现“代码雨”类似黑客帝国文字下落效果


Posted in Javascript onMarch 17, 2020

先看看JS+CSS+HTML实现“代码雨”类似黑客帝国文字下落最终效果:

JS+CSS+HTML实现“代码雨”类似黑客帝国文字下落效果

HTML代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/ok.css" rel="external nofollow" >
<title>code by-zhenyu.sha</title>
</head>
 
<body>
<canvas id="canvas"></canvas>
</body>
<script src="http://www.jq22.com/jquery/jquery-1.10.2.js"></script>
<script src="http://neilcarpenter.com/demos/canvas/matrix/stats.min.js"></script>
<script type="text/javascript" src="js/ok.js"></script>
</html>

js代码:

(function() {
  var lastTime = 0;
  var vendors = ['ms', 'moz', 'webkit', 'o'];
  for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
    window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
    window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] ||
      window[vendors[x] + 'CancelRequestAnimationFrame'];
  }
  if (!window.requestAnimationFrame)
    window.requestAnimationFrame = function(callback, element) {
      var currTime = new Date().getTime();
      var timeToCall = Math.max(0, 16 - (currTime - lastTime));
      var id = window.setTimeout(function() {
          callback(currTime + timeToCall);
        },
        timeToCall);
      lastTime = currTime + timeToCall;
      return id;
    };
  if (!window.cancelAnimationFrame)
    window.cancelAnimationFrame = function(id) {
      clearTimeout(id);
    };
}());
// stats
var stats = new Stats();
stats.setMode(0);
stats.domElement.style.position = 'absolute';
stats.domElement.style.left = '0px';
stats.domElement.style.top = '0px';
document.body.appendChild(stats.domElement);
var M = {
  settings: {
    COL_WIDTH: 20,
    COL_HEIGHT: 25,
    VELOCITY_PARAMS: {
      min: 4,
      max: 8
    },
    CODE_LENGTH_PARAMS: {
      min: 20,
      max: 40
    }
  },
  animation: null,
  c: null,
  ctx: null,
  lineC: null,
  ctx2: null,
  WIDTH: window.innerWidth,
  HEIGHT: window.innerHeight,
  COLUMNS: null,
  canvii: [],
  font: '30px matrix-code',
  letters: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '$', '+', '-', '*', '/', '=', '%', '"', '\'', '#', '&', '_', '(', ')', ',', '.', ';', ':', '?', '!', '\\', '|', '{', '}', '<', '>', '[', ']', '^', '~'],
  codes: [],
  createCodeLoop: null,
  codesCounter: 0,
  init: function() {
    M.c = document.getElementById('canvas');
    M.ctx = M.c.getContext('2d');
    M.c.width = M.WIDTH;
    M.c.height = M.HEIGHT;
    M.ctx.shadowBlur = 0;
    M.ctx.fillStyle = '#000';
    M.ctx.fillRect(0, 0, M.WIDTH, M.HEIGHT);
    M.ctx.font = M.font;
    M.COLUMNS = Math.ceil(M.WIDTH / M.settings.COL_WIDTH);
    for (var i = 0; i < M.COLUMNS; i++) {
      M.codes[i] = [];
      M.codes[i][0] = {
        'open': true,
        'position': {
          'x': 0,
          'y': 0
        },
        'strength': 0
      };
    }
    M.loop();
    M.createLines();
    M.createCode();
    // not doing this, kills CPU
    // M.swapCharacters();
    window.onresize = function() {
      window.cancelAnimationFrame(M.animation);
      M.animation = null;
      M.ctx.clearRect(0, 0, M.WIDTH, M.HEIGHT);
      M.codesCounter = 0;
      M.ctx2.clearRect(0, 0, M.WIDTH, M.HEIGHT);
      M.WIDTH = window.innerWidth;
      M.HEIGHT = window.innerHeight;
      M.init();
    };
  },
  loop: function() {
    M.animation = requestAnimationFrame(function() {
      M.loop();
    });
    M.draw();
    stats.update();
  },
  draw: function() {
    var velocity, height, x, y, c, ctx;
    // slow fade BG colour
    M.ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
    M.ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
    M.ctx.fillRect(0, 0, M.WIDTH, M.HEIGHT);
    M.ctx.globalCompositeOperation = 'source-over';
    for (var i = 0; i < M.COLUMNS; i++) {
      // check member of array isn't undefined at this point
      if (M.codes[i][0].canvas) {
        velocity = M.codes[i][0].velocity;
        height = M.codes[i][0].canvas.height;
        x = M.codes[i][0].position.x;
        y = M.codes[i][0].position.y - height;
        c = M.codes[i][0].canvas;
        ctx = c.getContext('2d');
        M.ctx.drawImage(c, x, y, M.settings.COL_WIDTH, height);
        if ((M.codes[i][0].position.y - height) < M.HEIGHT) {
          M.codes[i][0].position.y += velocity;
        } else {
          M.codes[i][0].position.y = 0;
        }
      }
    }
  },
  createCode: function() {
    if (M.codesCounter > M.COLUMNS) {
      clearTimeout(M.createCodeLoop);
      return;
    }
    var randomInterval = M.randomFromInterval(0, 100);
    var column = M.assignColumn();
    if (column) {
      var codeLength = M.randomFromInterval(M.settings.CODE_LENGTH_PARAMS.min, M.settings.CODE_LENGTH_PARAMS.max);
      var codeVelocity = (Math.random() * (M.settings.VELOCITY_PARAMS.max - M.settings.VELOCITY_PARAMS.min)) + M.settings.VELOCITY_PARAMS.min;
      var lettersLength = M.letters.length;
      M.codes[column][0].position = {
        'x': (column * M.settings.COL_WIDTH),
        'y': 0
      };
      M.codes[column][0].velocity = codeVelocity;
      M.codes[column][0].strength = M.codes[column][0].velocity / M.settings.VELOCITY_PARAMS.max;
      for (var i = 1; i <= codeLength; i++) {
        var newLetter = M.randomFromInterval(0, (lettersLength - 1));
        M.codes[column][i] = M.letters[newLetter];
      }
      M.createCanvii(column);
      M.codesCounter++;
    }
    M.createCodeLoop = setTimeout(M.createCode, randomInterval);
  },
  createCanvii: function(i) {
    var codeLen = M.codes[i].length - 1;
    var canvHeight = codeLen * M.settings.COL_HEIGHT;
    var velocity = M.codes[i][0].velocity;
    var strength = M.codes[i][0].strength;
    var text, fadeStrength;
    var newCanv = document.createElement('canvas');
    var newCtx = newCanv.getContext('2d');
    newCanv.width = M.settings.COL_WIDTH;
    newCanv.height = canvHeight;
    for (var j = 1; j < codeLen; j++) {
      text = M.codes[i][j];
      newCtx.globalCompositeOperation = 'source-over';
      newCtx.font = '30px matrix-code';
      if (j < 5) {
        newCtx.shadowColor = 'hsl(104, 79%, 74%)';
        newCtx.shadowOffsetX = 0;
        newCtx.shadowOffsetY = 0;
        newCtx.shadowBlur = 10;
        newCtx.fillStyle = 'hsla(104, 79%, ' + (100 - (j * 5)) + '%, ' + strength + ')';
      } else if (j > (codeLen - 4)) {
        fadeStrength = j / codeLen;
        fadeStrength = 1 - fadeStrength;
        newCtx.shadowOffsetX = 0;
        newCtx.shadowOffsetY = 0;
        newCtx.shadowBlur = 0;
        newCtx.fillStyle = 'hsla(104, 79%, 74%, ' + (fadeStrength + 0.3) + ')';
      } else {
        newCtx.shadowOffsetX = 0;
        newCtx.shadowOffsetY = 0;
        newCtx.shadowBlur = 0;
        newCtx.fillStyle = 'hsla(104, 79%, 74%, ' + strength + ')';
      }
      newCtx.fillText(text, 0, (canvHeight - (j * M.settings.COL_HEIGHT)));
    }
    M.codes[i][0].canvas = newCanv;
  },
  swapCharacters: function() {
    var randomCodeIndex;
    var randomCode;
    var randomCodeLen;
    var randomCharIndex;
    var newRandomCharIndex;
    var newRandomChar;
    for (var i = 0; i < 20; i++) {
      randomCodeIndex = M.randomFromInterval(0, (M.codes.length - 1));
      randomCode = M.codes[randomCodeIndex];
      randomCodeLen = randomCode.length;
      randomCharIndex = M.randomFromInterval(2, (randomCodeLen - 1));
      newRandomCharIndex = M.randomFromInterval(0, (M.letters.length - 1));
      newRandomChar = M.letters[newRandomCharIndex];
      randomCode[randomCharIndex] = newRandomChar;
    }
    M.swapCharacters();
  },
  createLines: function() {
    M.linesC = document.createElement('canvas');
    M.linesC.width = M.WIDTH;
    M.linesC.height = M.HEIGHT;
    M.linesC.style.position = 'absolute';
    M.linesC.style.top = 0;
    M.linesC.style.left = 0;
    M.linesC.style.zIndex = 10;
    document.body.appendChild(M.linesC);
    var linesYBlack = 0;
    var linesYWhite = 0;
    M.ctx2 = M.linesC.getContext('2d');
    M.ctx2.beginPath();
    M.ctx2.lineWidth = 1;
    M.ctx2.strokeStyle = 'rgba(0, 0, 0, 0.7)';
    while (linesYBlack < M.HEIGHT) {
      M.ctx2.moveTo(0, linesYBlack);
      M.ctx2.lineTo(M.WIDTH, linesYBlack);
      linesYBlack += 5;
    }
    M.ctx2.lineWidth = 0.15;
    M.ctx2.strokeStyle = 'rgba(255, 255, 255, 0.7)';
    while (linesYWhite < M.HEIGHT) {
      M.ctx2.moveTo(0, linesYWhite + 1);
      M.ctx2.lineTo(M.WIDTH, linesYWhite + 1);
      linesYWhite += 5;
    }
    M.ctx2.stroke();
  },
  assignColumn: function() {
    var randomColumn = M.randomFromInterval(0, (M.COLUMNS - 1));
    if (M.codes[randomColumn][0].open) {
      M.codes[randomColumn][0].open = false;
    } else {
      return false;
    }
    return randomColumn;
  },
  randomFromInterval: function(from, to) {
    return Math.floor(Math.random() * (to - from + 1) + from);
  },
  snapshot: function() {
    window.open(M.c.toDataURL());
  }
};
function eventListenerz() {
  var controlToggles = document.getElementsByClassName('toggle-info');
  var controls = document.getElementById('info');
  var snapshotBtn = document.getElementById('snapshot');
  function toggleControls(e) {
    e.preventDefault();
    controls.className = controls.className === 'closed' ? '' : 'closed';
  }
  for (var j = 0; j < 2; j++) {
    controlToggles[j].addEventListener('click', toggleControls, false);
  }
  snapshotBtn.addEventListener('click', M.snapshot, false);
}
window.onload = function() {
  M.init();
  eventListenerz();
};

css代码:

@import url("http://fonts.googleapis.com/css?family=Carrois+Gothic");
@font-face {
  font-family: 'matrix-code';
  src: url('http://neilcarpenter.com/demos/canvas/matrix/font/matrix-code.eot?#iefix') format('embedded-opentype'), url('http://neilcarpenter.com/demos/canvas/matrix/font/matrix-code.woff') format('woff'), url('http://neilcarpenter.com/demos/canvas/matrix/font/matrix-code.ttf') format('truetype'), url('http://neilcarpenter.com/demos/canvas/matrix/font/matrix-code.svg#svgFontName') format('svg');
}
html,
body {
  -webkit-font-smoothing: antialiased;
  font: normal 12px/14px "Carrois Gothic", sans-serif;
  width: 100%;
  height: 100%;
  margin: 0;
  overflow: hidden;
  color: #fff;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
body {
  background: black;
}
#stats {
  z-index: 100;
}
#info {
  background: rgba(0, 0, 0, 0.7);
  position: fixed;
  bottom: 0;
  left: 0px;
  width: 250px;
  padding: 10px 20px 20px;
  z-index: 100;
  -webkit-transform-origin: bottom center;
  -moz-transform-origin: bottom center;
  -o-transform-origin: bottom center;
  transform-origin: bottom center;
  -webkit-transform: rotate(0deg);
  -moz-transform: rotate(0deg);
  -o-transform: rotate(0deg);
  transform: rotate(0deg);
  -webkit-transition: -webkit-transform .5s ease-in-out;
  -moz-transition: -moz-transform .5s ease-in-out;
  -o-transition: -o-transform .5s ease-in-out;
  transition: transform .5s ease-in-out;
}
#info.closed {
  -webkit-transform: rotate(180deg);
  -moz-transform: rotate(180deg);
  -o-transform: rotate(180deg);
  transform: rotate(180deg);
}
.toggle-info {
  position: absolute;
  display: block;
  height: 10px;
  background: rgba(0, 0, 0, 0.8);
  width: 290px;
  left: 0;
  text-align: center;
  padding: 3px 0 7px;
  text-decoration: none;
  color: white;
  text-shadow: none;
}
.toggle-info:hover {
  background: rgb(0, 0, 0);
}
#close {
  top: -20px;
}
#open {
  bottom: -20px;
  -webkit-transform: rotate(-180deg);
  -moz-transform: rotate(-180deg);
  -o-transform: rotate(-180deg);
  transform: rotate(-180deg);
}
button {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
  border: 0;
  border-radius: 2px;
  padding: 7px 10px;
  box-shadow: 0 0 3px 0px rgba(255, 255, 255, 0.3);
  cursor: pointer;
}
button:hover {
  background: rgba(255, 255, 255, 0.1);
}
pa {
  color: #fff;
}
pa:hover {
  color: #EFFDEB;
  text-shadow: 0px 0px 5px #75AD61;
}

本文介绍了使用JS+CSS+HTML实现“代码雨”类似黑客帝国文字下落效果的代码实例,更多JS特效请查看下面的相关链接

Javascript 相关文章推荐
jQuery ui 1.7更新小结
Aug 15 Javascript
JavaScript Event学习第五章 高级事件注册模型
Feb 07 Javascript
基于jquery的inputlimiter 实现字数限制功能
May 30 Javascript
Js中setTimeout()和setInterval() 何时被调用执行的用法
Apr 12 Javascript
Javascript 按位与赋值运算符 (&amp;=)使用介绍
Feb 04 Javascript
jQuery实现手机上输入后隐藏键盘功能
Jan 04 Javascript
Easyui Tree获取当前选择节点的所有顶级父节点
Feb 14 Javascript
利用imgareaselect辅助后台实现图片上传裁剪
Mar 02 Javascript
vue.js事件处理器是什么
Mar 20 Javascript
js实现随机数字字母验证码
Jun 19 Javascript
vue指令只能输入正数并且只能输入一个小数点的方法
Jun 08 Javascript
Vue3.0结合bootstrap创建多页面应用
May 28 Javascript
js实现简单点赞操作
Mar 17 #Javascript
vue+ESLint 配置保存 自动格式化代码
Mar 17 #Javascript
HTML+JS实现“代码雨”效果源码(黑客帝国文字下落效果)
Mar 17 #Javascript
JavaScript实现横版菜单栏
Mar 17 #Javascript
JavaScript实现留言板案例
Mar 17 #Javascript
es6函数之严格模式用法实例分析
Mar 17 #Javascript
JavaScript实现字符串与HTML格式相互转换
Mar 17 #Javascript
You might like
PHP Token(令牌)设计
2008/03/15 PHP
php单一接口的实现方法
2015/06/20 PHP
Yii2表单事件之Ajax提交实现方法
2017/05/04 PHP
Yii框架批量插入数据扩展类的简单实现方法
2017/05/23 PHP
PHP dirname简单使用代码实例
2020/11/13 PHP
PHP中SESSION过期设置
2021/03/09 PHP
JavaScript版代码高亮
2006/06/26 Javascript
jQuery each()小议
2010/03/18 Javascript
JavaScript编程中容易出BUG的几点小知识
2015/01/31 Javascript
js实现动画特效的文字链接鼠标悬停提示的方法
2015/03/02 Javascript
js实现鼠标点击文本框自动选中内容的方法
2015/08/20 Javascript
jQuery+jsp下拉框联动获取本地数据的方法(附源码)
2015/12/03 Javascript
js实现搜索框关键字智能匹配代码
2020/03/26 Javascript
javascript实现去除HTML标签的方法
2016/12/26 Javascript
使用bat打开多个cmd窗口执行gulp、node
2017/02/17 Javascript
vue中用动态组件实现选项卡切换效果
2017/03/25 Javascript
理解javascript async的用法
2017/08/22 Javascript
JavaScript正则表达式的贪婪匹配和非贪婪匹配
2017/09/05 Javascript
JS实现预加载视频音频/视频获取截图(返回canvas截图)
2017/10/09 Javascript
使用JS中的Replace()方法遇到的问题小结
2017/10/20 Javascript
Vue.js中的computed工作原理
2018/03/22 Javascript
vue-dplayer 视频播放器实例代码
2019/11/08 Javascript
聊聊Vue中provide/inject的应用详解
2019/11/10 Javascript
[02:37]2018DOTA2亚洲邀请赛赛前采访 VP.no[o]ne心中最强SOLO是谁
2018/04/04 DOTA
[01:10]为家乡而战!完美世界城市挑战赛全国总决赛花絮
2019/07/25 DOTA
python验证码识别的实例详解
2016/09/09 Python
Python 基础教程之闭包的使用方法
2017/09/29 Python
Python用字典构建多级菜单功能
2019/07/11 Python
python 如何去除字符串头尾的多余符号
2019/11/19 Python
Python使用Paramiko控制liunx第三方库
2020/05/20 Python
阿迪达斯奥地利官方商城:adidas.at
2016/10/16 全球购物
社区工作者感言
2014/03/02 职场文书
报关报检委托书
2014/04/08 职场文书
教师批评与自我批评总结
2014/10/16 职场文书
2014年妇女工作总结
2014/12/06 职场文书
综合素质评价自我评价
2015/03/06 职场文书