使用canvas制作下雨的效果

要使用HTML5的<canvas>元素来制作下雨效果,你需要遵循以下步骤:

  1. 设置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>
        body { margin: 0; overflow: hidden; }
        canvas { background: #000; display: block; }
    </style>
</head>
<body>
    <canvas id="rainCanvas"></canvas>
    <script src="script.js"></script>
</body>
</html>
  1. 编写JavaScript代码 (script.js 文件):
const canvas = document.getElementById('rainCanvas');
const ctx = canvas.getContext('2d');

let rainDrops = []; // 存储雨滴的数组
const numDrops = 200; // 雨滴数量
const gravity = 0.2; // 重力加速度

// 设置canvas大小
function resize() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
}
resize();
window.onresize = resize;

// 雨滴构造函数
function RainDrop() {
    this.x = Math.random() * canvas.width; // 随机x位置
    this.y = Math.random() * canvas.height; // 随机y位置
    this.length = Math.random() * 5 + 1; // 雨滴长度
    this.speed = Math.random() * 5 + 1; // 雨滴下落速度
    this.opacity = Math.random(); // 雨滴透明度
}

// 更新雨滴位置
RainDrop.prototype.update = function() {
    this.y += this.speed + gravity; // 下落,受速度和重力影响
    if (this.y > canvas.height) { // 如果雨滴落出画布,则重置位置
        this.y = 0;
        this.x = Math.random() * canvas.width;
    }
}

// 绘制雨滴
RainDrop.prototype.draw = function() {
    ctx.beginPath();
    ctx.globalAlpha = this.opacity; // 设置透明度
    ctx.moveTo(this.x, this.y);
    ctx.lineTo(this.x + 1, this.y + this.length); // 绘制线条表示雨滴
    ctx.strokeStyle = '#fff'; // 设置雨滴颜色
    ctx.stroke(); // 绘制雨滴
}

// 初始化雨滴
function init() {
    for (let i = 0; i < numDrops; i++) {
        rainDrops.push(new RainDrop());
    }
}
init();

// 动画循环
function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布
    for (let drop of rainDrops) { // 更新和绘制每个雨滴
        drop.update();
        drop.draw();
    }
    requestAnimationFrame(animate); // 循环动画
}
animate();

这段代码首先设置了HTML结构,并链接到一个外部的JavaScript文件。在JavaScript文件中,我们定义了一个RainDrop构造函数来表示每个雨滴,以及相关的更新和绘制方法。我们还设置了一个动画循环来持续更新和绘制雨滴,从而创建下雨的效果。

posted @ 2025-01-12 09:10  王铁柱6  阅读(52)  评论(0)    收藏  举报