如果文章对你有收获,还请不要吝啬【点赞??收藏?评论?】三连哦,你的鼓励将是我成长助力之一!谢谢!
先看实现效果
再看完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rain Effect</title>
<!-- <link rel="stylesheet" href="styles.css"> -->
<!--
HTML:
创建一个canvas元素用于绘制雨滴。
CSS:
设置body的背景为黑色,并隐藏滚动条。
JavaScript:
创建一个Raindrop类,用于表示单个雨滴。
Raindrop类包含位置、长度、速度和透明度等属性,并提供update和draw方法。
createRaindrops函数用于创建指定数量的雨滴。
animate函数用于动画循环,不断更新和绘制雨滴。
监听窗口大小变化事件,调整canvas的大小。
-->
<style type="text/css">
body {
margin: 0;
overflow: hidden;
background: #000;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="rainCanvas"></canvas>
<!-- <script src="script.js"></script> -->
<script type="text/javascript">
const canvas = document.getElementById('rainCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const raindrops = [];
class Raindrop {
constructor() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.length = Math.random() * 5 + 2; // 雨滴长度
this.speed = Math.random() * 4 + 2; // 下雨的速度
this.opacity = Math.random() * 0.5 + 0.5; // 雨滴透明度
}
update() {
this.y += this.speed;
if (this.y > canvas.height) {
this.y = -this.length;
this.x = Math.random() * canvas.width;
}
}
draw() {
ctx.beginPath();
ctx.moveTo(this.x, this.y);
ctx.lineTo(this.x, this.y + this.length);
ctx.strokeStyle = `rgba(174,194,224,${this.opacity})`;
ctx.lineWidth = 5;
ctx.lineCap = 'round';
ctx.stroke();
}
}
function createRaindrops(num) {
for (let i = 0; i < num; i++) {
raindrops.push(new Raindrop());
}
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
raindrops.forEach(raindrop => {
raindrop.update();
raindrop.draw();
});
requestAnimationFrame(animate);
}
createRaindrops(100); // 创建200个雨滴
animate();
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
如果文章对你有收获,还请不要吝啬【点赞??收藏?评论?】三连哦,你的鼓励将是我成长助力之一!谢谢!