效果预览:效果预览
源码下载:关注公众号【RMRF】,回复【css13】可获取源码
1、使用<canvas>
元素创建了一个画布,用于绘制数字雨的效果
2、创建一个数组 arrs 来记录每一列的位置
3、并用随机的绿色和字体大小来绘制随机数字,同时更新 arrs 数组,模拟数字的下落
4、如果数字下落到底部或达到一定概率,重置数字位置
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>数字雨</title>
<style>
/* 清除所有元素的内外边距 */
* {
padding: 0px;
margin: 0px;
}
/* 设置页面样式 */
body {
height: 100vh;
width: 100vw;
overflow: hidden;
background: #000;
}
</style>
</head>
<body>
<!-- 创建画布元素 -->
<canvas id="canvas"></canvas>
</body>
<script>
</script>
</html>
JavaScript
const canvas = document.getElementById("canvas")
const ctx = canvas.getContext("2d")
const fontSize = 20
let rows, columns, arrs
// 自适应
function resizeCanvas() {
const width = window.innerWidth || document.documentElement.clientWidth
const height = window.innerHeight || document.documentElement.clientHeight
canvas.width = width
canvas.height = height
rows = Math.ceil(height / fontSize)
columns = Math.ceil(width / fontSize)
arrs = new Array(columns).fill(0)
}
// 动画
function animation() {
ctx.fillStyle = "rgba(0,0,0,0.1)"
ctx.fillRect(0, 0, canvas.width, canvas.height)
for (let i = 0; i < columns; i++) {
ctx.fillStyle = "green"
ctx.font = `${fontSize}px 宋体`
ctx.fillText(Math.floor(Math.random() * 10), fontSize * i, arrs[i] * fontSize)
arrs[i]++
if (arrs[i] > rows || Math.random() > 0.98) {
arrs[i] = 0
}
}
setTimeout(() => {
animation()
}, 20)
}
// 初始化
function init() {
resizeCanvas()
window.addEventListener("resize", resizeCanvas)
animation()
}
init()