/* CSS部分 */
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
width: 100%;
height: 100vh;
overflow: hidden;
}
canvas {
background-color: #000;
}
<!-- html部分 --> <canvas></canvas>
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const w = window.innerWidth,
h = window.innerHeight,
fontSize = 26;
// 设置canvas大小
canvas.width = w;
canvas.height = h;
// 设置canvas渲染的文字大小与字体
ctx.font = `${fontSize}px "微软雅黑"`;
// 编写随机获取颜色 和字符 函数 默认返回随机字符,传入true返回随机颜色
function getRandomContent(type = false) {
// 定义随机颜色数组
const colorArr = [
"#FFFFFF",
"#FF3366",
"#33CCFF",
"#FFFF33",
"#66FF66",
"#CC66FF",
"#FF9933",
"#FF6666",
"#33FFCC",
"#9966FF",
"#FFCC00",
"#3366FF",
"#66CC99",
"#FF66CC",
"#CCFFFF",
"#FFCC99",
];
// 定义完成字符
const str = 'print("HelloWorld");';
// 根据type值判断返回的数据
const returnData = type ? colorArr : str;
return returnData[Math.floor(Math.random() * returnData.length)];
}
// 计算每列可以存放多少个字符
const rowStrNum = Math.floor(w / fontSize);
// 定义数组 用于存储每列
const dataArrCol = new Array(rowStrNum).fill(0);
// 开始绘制文字
function drawText() {
// 每次绘制之前 先覆盖一层蒙版
ctx.fillStyle = "rgba(0,0,0,.15)";
ctx.fillRect(0, 0, w, h);
dataArrCol.forEach((item, index) => {
// 每次循环 获取一个新的颜色和字符
const color = getRandomContent(true);
const text = getRandomContent();
// 计算文字所在的位置 x y
const x = fontSize * index + 10,
y = (fontSize + 6) * (item + 1);
// 设置文字颜色
ctx.fillStyle = color;
ctx.fillText(text, x, y);
// 判断边界 增加随机条件,让元素随机返回第一行 实现错落效果
if (fontSize * item > h && Math.random() > 0.9) {
dataArrCol[index] = 0;
} else {
// 每次循环结束前 让数组的item+1
dataArrCol[index] = item + 1;
}
});
}
drawText();
setInterval(drawText, 40);
评论 (0)