简单操作一下canvas,实现一个比较好看的效果
const rain = (function() {
// 第一次下雨需要计算随机y值,要不然一行代码是同一高度降落的
let hasRain = false;
return function () {
ctx.fillStyle = 'rgba(0,0,0,0.05)';
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.fillStyle = '#0f0';
Arr.forEach((item, index) => {
if (!hasRain) {
item = Math.random() * canvas.height;
}
const text = strArr[Math.floor(Math.random() * strArr.length)];
ctx.fillText(text, index * 10, item+ 10);
Arr[index] =
item > canvas.height
// 下面这行加不加都行,是为了实现类似瀑布的效果,不加也一样好看
|| item > canvas.height * 10 * Math.random()
? 0 : item + 10;
});
hasRain = true;
}
})();
setInterval(() => {
console.time('rain');
rain();
console.timeEnd('rain');
}, 40)
随便建一个index.html引入
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
overflow: hidden;
}
html, body {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="./codeRain.js"></script>
</body>
</html>
实现效果如下
ps:一个摸鱼的下午闲来无事,就看到了一个比较好看的效果图,就照着随便写了写。不是纯手写,有百度的成分 嘿嘿 😁