新增第215个小实例:黑客帝国“代码雨”特效

This commit is contained in:
DESKTOP-BM6RJU5\wyanh 2023-04-06 17:55:08 +08:00
parent a894967202
commit f4300de0f6
4 changed files with 85 additions and 0 deletions

View File

@ -222,6 +222,7 @@
212. HTML5+CSS3小实例纯CSS实现弧边选项卡
213. HTML5+CSS3小实例旋转彩色loading加载动画
214. HTML5+CSS3小实例创意修剪路径图像悬停效果
215. HTML5+CSS3+JS小实例黑客帝国“代码雨”特效
#### 赞赏作者
![image](https://gitee.com/wyanhui02/html_css_demo/raw/master/images/%E8%B5%9E%E8%B5%8F%E4%BD%9C%E8%80%85/%E8%B5%9E%E8%B5%8F%E7%A0%81.jpg)

12
code/215/215.css Normal file
View File

@ -0,0 +1,12 @@
*{
margin: 0;
padding: 0;
}
body{
overflow: hidden;
}
canvas{
background-color: #000;
width: 100vw;
height: 100vh;
}

15
code/215/215.html Normal file
View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>黑客帝国“代码雨”特效</title>
<link rel="stylesheet" href="215.css">
</head>
<body>
<canvas></canvas>
</body>
</html>
<script src="215.js"></script>

57
code/215/215.js Normal file
View File

@ -0,0 +1,57 @@
// 要操作的画布
const cvs=document.querySelector('canvas');
// 画布上下文
const ctx=cvs.getContext('2d');
// 初始化画布宽高
function init(){
cvs.width=window.innerWidth * devicePixelRatio;
cvs.height=window.innerHeight * devicePixelRatio;
}
init();
// 根据DPR计算字体的大小devicePixelRatio 设备像素比)
const fontSize=20 * devicePixelRatio;
// 设置字体、字体大小和CSS设置字体一样
ctx.font=`${fontSize}px "Consolas"`;
// 计算总列数fontSize相当于每列的宽度
const columnCount=Math.floor(cvs.width / fontSize);
// 根据列数创建数组并填充为0
const charIndex=new Array(columnCount).fill(0);
// 绘制代码雨
function draw(){
// 加个渐隐效果
ctx.fillStyle='rgba(0,0,0,0.1)';
ctx.fillRect(0,0,cvs.width,cvs.height);
// 设置字体颜色
ctx.fillStyle='#6be445';
// 设置文本基线为顶部
ctx.textBaseline='top';
for(let i=0;i<columnCount;i++){
// 获取随机字符
const text=getRandomChar();
// 计算文字的x、y坐标
const x=i*fontSize;
const y=charIndex[i]*fontSize;
// 绘制文本
ctx.fillText(text,x,y);
// 超出画布归零
// 这里需要再加个判断使之错开归零的时间点Math.random()>0.99
if(y>cvs.height && Math.random()>0.99){
charIndex[i]=0;
}else{
charIndex[i]++;
}
}
}
// 开始绘制
draw();
// 每个50毫秒绘制一次
setInterval(draw,50);
// 获取随机字符
function getRandomChar(){
const str='0123456789abcdefghijklmnopqrstuvwxyz';
return str[Math.floor(Math.random() * str.length)];
}