HTML5 Canvas 中实现喷泉效果

891 阅读2分钟

要在 HTML5 Canvas 中实现喷泉效果,我们可以使用 JavaScript 动态绘制水滴,并模拟水滴从喷泉中流出的效果。下面是一个简单的示例,创建一个喷泉动画

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas 喷泉效果</title>
    <style>
        body {
            margin: 0;
            background-color: #87CEEB;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        canvas {
            border: 2px solid #000;
        }
    </style>
</head>
<body>
    <canvas id="canvas" width="800" height="600"></canvas>
    <script>
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');

        const particles = [];
        const particleCount = 100;

        class Particle {
            constructor(x, y) {
                this.x = x;
                this.y = y;
                this.size = Math.random() * 5 + 2;
                this.speedY = Math.random() * -3 - 1; // 向上的速度
                this.gravity = 0.1; // 重力加速度
                this.alpha = 1; // 透明度
            }

            update() {
                this.y += this.speedY; // 更新y坐标
                this.speedY += this.gravity; // 应用重力
                this.alpha -= 0.01; // 渐变透明
                
                // Reset the particle if it's out of canvas
                if (this.alpha <= 0) {
                    this.reset();
                }
            }

            reset() {
                this.x = Math.random() * canvas.width; // 随机x坐标
                this.y = canvas.height; // 重置到底部
                this.size = Math.random() * 5 + 2; // 随机大小
                this.speedY = Math.random() * -3 - 1; // 随机速度
                this.alpha = 1; // 透明度重置
            }

            draw() {
                ctx.fillStyle = `rgba(255, 255, 255, ${this.alpha})`; // 白色水滴
                ctx.beginPath();
                ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
                ctx.fill();
            }
        }

        for (let i = 0; i < particleCount; i++) {
            particles.push(new Particle(Math.random() * canvas.width, canvas.height));
        }

        function animate() {
            ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空画布

            for (let i = 0; i < particles.length; i++) {
                particles[i].update(); // 更新粒子
                particles[i].draw(); // 绘制粒子
            }

            requestAnimationFrame(animate); // 循环调用
        }

        animate();
    </script>
</body>
</html>

说明

  1. 粒子类:每个水滴(粒子)都有随机的 x 坐标、大小、向上的速度、重力效果和透明度。
  2. 更新与重置:在每一帧中,水滴的 y 坐标和速度会更新。透明度会逐渐降低,若透明度降低到 0,则会重置到画布底部,准备重新喷出。
  3. 绘制效果:使用 Canvas 的 arc 方法绘制每个水滴,并根据其透明度调整颜色。

使用方法

  1. 创建一个新的 HTML 文件,命名为 index.html
  2. 将上述代码粘贴到该文件中。
  3. 使用浏览器打开 index.html 文件,即可查看喷泉效果。

这个示例展示了一个简单的喷泉动画,您可以根据需要调整粒子的数量、速度和其他参数,以实现更复杂的效果。