音效素材网提供各类素材,打造精品素材网站!

站内导航 站长工具 投稿中心 手机访问

音效素材

HTML实现代码雨源码及效果示例
日期:2021-09-04 20:53:39   来源:脚本之家

最近学习了HTML,今天写个HTML代码雨,然后下面用HTML和js也写了一个,给自己留点笔记

先看看效果

1、绿色:

HTML实现代码雨源码及效果示例

2、彩色:

HTML实现代码雨源码及效果示例

3、背景色:

HTML实现代码雨源码及效果示例

4、绿色逐渐变浅:

HTML实现代码雨源码及效果示例

源代码:

<!DOCTYPE html>
<html>
   
<head>   
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <title>Code -by ZhenYu.Sha</title>
    <style type="text/css">
        html, body {
            width: 100%;
            height: 100%;
        }
        body {
            background: #000;
            overflow: hidden;
            margin: 0;
            padding: 0;
        }
    </style>
</head>
   
<body>  
<canvas id="cvs"></canvas>
<script type="text/javascript">
    var cvs = document.getElementById("cvs");
    var ctx = cvs.getContext("2d");
    var cw = cvs.width = document.body.clientWidth;
    var ch = cvs.height = document.body.clientHeight;
    //动画绘制对象
    var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
    var codeRainArr = []; //代码雨数组
    var cols = parseInt(cw / 14); //代码雨列数
    var step = 16;    //步长,每一列内部数字之间的上下间隔
    ctx.font = "bold 26px microsoft yahei"; //声明字体,个人喜欢微软雅黑
 
    function createColorCv() {
        //画布基本颜色
        ctx.fillStyle = "#242424";
        ctx.fillRect(0, 0, cw, ch);
    }
 
    //创建代码雨
    function createCodeRain() {
        for (var n = 0; n < cols; n++) {
            var col = [];
            //基础位置,为了列与列之间产生错位
            var basePos = parseInt(Math.random() * 300);
            //随机速度 3~13之间
            var speed = parseInt(Math.random() * 10) + 3;
            //每组的x轴位置随机产生
            var colx = parseInt(Math.random() * cw)
 
            //绿色随机
            var rgbr = 0;
            var rgbg = parseInt(Math.random() * 255);
            var rgbb = 0;
            //ctx.fillStyle = "rgb("+r+','+g+','+b+")"
 
            for (var i = 0; i < parseInt(ch / step) / 2; i++) {
                var code = {
                    x: colx,
                    y: -(step * i) - basePos,
                    speed: speed,
                    //  text : parseInt(Math.random()*10)%2 == 0 ? 0 : 1  //随机生成0或者1
                    text: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "s", "t", "u", "v", "w", "x", "y", "z"][parseInt(Math.random() * 11)], //随机生成字母数组中的一个
                    color: "rgb(" + rgbr + ',' + rgbg + ',' + rgbb + ")"
                }
                col.push(code);
            }
            codeRainArr.push(col);
        }
    }
 
    //代码雨下起来
    function codeRaining() {
        //把画布擦干净
        ctx.clearRect(0, 0, cw, ch);
        //创建有颜色的画布
        //createColorCv();
        for (var n = 0; n < codeRainArr.length; n++) {
            //取出列
            col = codeRainArr[n];
            //遍历列,画出该列的代码
            for (var i = 0; i < col.length; i++) {
                var code = col[i];
                if (code.y > ch) {
                    //如果超出下边界则重置到顶部
                    code.y = 0;
                } else {
                    //匀速降落
                    code.y += code.speed;
                }
                
                //1 颜色也随机变化
                //ctx.fillStyle = "hsl("+(parseInt(Math.random()*359)+1)+",30%,"+(50-i*2)+"%)"; 
 
                //2 绿色逐渐变浅
                // ctx.fillStyle = "hsl(123,80%,"+(30-i*2)+"%)"; 
 
                //3 绿色随机
                // var r= 0;
                // var g= parseInt(Math.random()*255) + 3;
                // var b= 0;
                // ctx.fillStyle = "rgb("+r+','+g+','+b+")";
 
                //4 一致绿
                ctx.fillStyle = code.color;
 
 
                //把代码画出来
                ctx.fillText(code.text, code.x, code.y);
            }
        }
        requestAnimationFrame(codeRaining);
    }
 
    //创建代码雨
    createCodeRain();
    //开始下雨吧 GO>>
    requestAnimationFrame(codeRaining);
</script>
   
</body>
</html>

更多代码雨的文章请参考我的其它文章:

“代码雨”js+css+html实现

HTML代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/ok.css">
<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;
}

 到此这篇关于HTML实现代码雨源码及效果示例的文章就介绍到这了,更多相关HTML代码雨内容请搜索以前的文章或继续浏览下面的相关文章,希望大家以后多多支持!

    您感兴趣的教程

    在docker中安装mysql详解

    本篇文章主要介绍了在docker中安装mysql详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编...

    详解 安装 docker mysql

    win10中文输入法仅在桌面显示怎么办?

    win10中文输入法仅在桌面显示怎么办?

    win10系统使用搜狗,QQ输入法只有在显示桌面的时候才出来,在使用其他程序输入框里面却只能输入字母数字,win10中...

    win10 中文输入法

    一分钟掌握linux系统目录结构

    这篇文章主要介绍了linux系统目录结构,通过结构图和多张表格了解linux系统目录结构,感兴趣的小伙伴们可以参考一...

    结构 目录 系统 linux

    PHP程序员玩转Linux系列 Linux和Windows安装

    这篇文章主要为大家详细介绍了PHP程序员玩转Linux系列文章,Linux和Windows安装nginx教程,具有一定的参考价值,感兴趣...

    玩转 程序员 安装 系列 PHP

    win10怎么安装杜比音效Doby V4.1 win10安装杜

    第四代杜比®家庭影院®技术包含了一整套协同工作的技术,让PC 发出清晰的环绕声同时第四代杜比家庭影院技术...

    win10杜比音效

    纯CSS实现iOS风格打开关闭选择框功能

    这篇文章主要介绍了纯CSS实现iOS风格打开关闭选择框,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作...

    css ios c

    Win7如何给C盘扩容 Win7系统电脑C盘扩容的办法

    Win7如何给C盘扩容 Win7系统电脑C盘扩容的

    Win7给电脑C盘扩容的办法大家知道吗?当系统分区C盘空间不足时,就需要给它扩容了,如果不管,C盘没有足够的空间...

    Win7 C盘 扩容

    百度推广竞品词的投放策略

    SEM是基于关键词搜索的营销活动。作为推广人员,我们所做的工作,就是打理成千上万的关键词,关注它们的质量度...

    百度推广 竞品词

    Visual Studio Code(vscode) git的使用教程

    这篇文章主要介绍了详解Visual Studio Code(vscode) git的使用,小编觉得挺不错的,现在分享给大家,也给大家做个参考。...

    教程 Studio Visual Code git

    七牛云储存创始人分享七牛的创立故事与

    这篇文章主要介绍了七牛云储存创始人分享七牛的创立故事与对Go语言的应用,七牛选用Go语言这门新兴的编程语言进行...

    七牛 Go语言

    Win10预览版Mobile 10547即将发布 9月19日上午

    微软副总裁Gabriel Aul的Twitter透露了 Win10 Mobile预览版10536即将发布,他表示该版本已进入内部慢速版阶段,发布时间目...

    Win10 预览版

    HTML标签meta总结,HTML5 head meta 属性整理

    移动前端开发中添加一些webkit专属的HTML5头部标签,帮助浏览器更好解析HTML代码,更好地将移动web前端页面表现出来...

    移动端html5模拟长按事件的实现方法

    这篇文章主要介绍了移动端html5模拟长按事件的实现方法的相关资料,小编觉得挺不错的,现在分享给大家,也给大家...

    移动端 html5 长按

    HTML常用meta大全(推荐)

    这篇文章主要介绍了HTML常用meta大全(推荐),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参...

    cdr怎么把图片转换成位图? cdr图片转换为位图的教程

    cdr怎么把图片转换成位图? cdr图片转换为

    cdr怎么把图片转换成位图?cdr中插入的图片想要转换成位图,该怎么转换呢?下面我们就来看看cdr图片转换为位图的...

    cdr 图片 位图

    win10系统怎么录屏?win10系统自带录屏详细教程

    win10系统怎么录屏?win10系统自带录屏详细

    当我们是使用win10系统的时候,想要录制电脑上的画面,这时候有人会想到下个第三方软件,其实可以用电脑上的自带...

    win10 系统自带录屏 详细教程

    + 更多教程 +
    HTMLCSSDreamweaverFrontpage