在他人的代码基础上,稍加修改,只为留作记忆,代码如下:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>代码流</title>
<style type="text/css">
html, body {
margin: 0px;
width: 100%;
height: 100%;
background: #000;
overflow: hidden;
}
canvas {
position: absolute;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas></canvas>
<script type="text/javascript">
var canvas = document.getElementsByTagName("canvas")[0];
//canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");
var C_H = document.body.clientHeight;
var C_W = document.body.clientWidth;
var FONT_SIZE = 14;
canvas.width = C_W;
canvas.height = C_H;
//计算一行能显示多少文字 浏览器宽/每个字大小 但是不能出现半个字
var clos = Math.floor(C_W / FONT_SIZE);
window.onresize = function () {
C_H = document.body.clientHeight;
C_W = document.body.clientWidth;
canvas.width = C_W;
canvas.height = C_H;
clos = Math.floor(C_W / FONT_SIZE);
}
var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var drops = [];
for (var i = 0; i < clos; i++) {
drops.push(GetNumber(false));
}
function drawString() {
//用黑色且透明度高的颜色来涂满整个画板区间,
//使得每次都将整个画板效果比之前的要现的更暗
ctx.fillStyle = "rgba(0,0,0,.05)";
ctx.fillRect(0, 0, C_W, C_H);
ctx.font = "700 " + FONT_SIZE + "px 微软雅黑";
//同一时刻填字一致
ctx.fillStyle = randomColor();//"#0f0";
for (var i = 0; i < clos; i++) {
if (drops[i] == NaN || drops[i] == undefined)//突然页面宽度变宽了,数组需要增加新成员
drops[i] = GetNumber(false);
var x = i * FONT_SIZE;
var y = drops[i] * FONT_SIZE;
//在这里,则同一时刻填字也不一致
ctx.fillStyle = randomColor();
if (y < C_H)//否则超出范围,不用填字
ctx.fillText(str[Math.floor(Math.random() * str.length)], x, y);
else {
var num = Math.random();
if (num > 0.99) drops[i] = 0;
}
drops[i]++;
}
setTimeout(function () {
requestAnimationFrame(function () { drawString() });
}, 30);
}
drawString();
//获取初始值
function GetNumber(isZero) {
if (isZero) return 0;
return Math.ceil(Math.random() * clos);
}
//随机颜色
function randomColor() {
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
return "rgb(" + r + "," + g + "," + b + ")"
}
</script>
</body>
</html>