使用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="fireworksCanvas"></canvas>
    <script src="fireworks.js"></script>
</body>
</html>
  1. 编写JavaScript代码 (fireworks.js):

以下是一个简化的烟花动画示例。这个示例会创建一个烟花,它会从底部飞向顶部并爆炸成粒子。

const canvas = document.getElementById('fireworksCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

class Particle {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.size = Math.random() * 5 + 1;
        this.speedY = -Math.random() * 3 - 1;
        this.speedX = Math.random() * 6 - 3;
        this.alpha = 1;
    }

    update() {
        this.x += this.speedX;
        this.y += this.speedY;
        this.alpha -= 0.01;
    }

    draw() {
        ctx.globalAlpha = this.alpha;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
        ctx.fillStyle = 'white';
        ctx.fill();
    }
}

class Firework {
    constructor() {
        this.x = Math.random() * canvas.width;
        this.y = canvas.height;
        this.particles = [];
        this.exploded = false;
    }

    update() {
        if (!this.exploded) {
            this.y -= 5;
            if (this.y < 0) {
                this.explode();
            }
        } else {
            this.particles.forEach((p, i) => {
                p.update();
                if (p.alpha < 0) {
                    this.particles.splice(i, 1);
                }
            });
        }
    }

    explode() {
        this.exploded = true;
        for (let i = 0; i < 100; i++) {
            this.particles.push(new Particle(this.x, this.y));
        }
    }

    draw() {
        if (!this.exploded) {
            ctx.beginPath();
            ctx.arc(this.x, this.y, 10, 0, Math.PI * 2);
            ctx.fillStyle = 'red';
            ctx.fill();
        } else {
            this.particles.forEach(p => p.draw());
        }
    }
}

const fireworks = [];
setInterval(() => {
    fireworks.push(new Firework());
}, 2000);

function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    fireworks.forEach((fw, i) => {
        fw.update();
        fw.draw();
        if (fw.particles.length === 0 && fw.exploded) {
            fireworks.splice(i, 1);
        }
    });
    requestAnimationFrame(animate);
}

animate();

这个代码示例创建了一个简单的烟花效果。你可以根据需要进一步扩展和优化它,例如添加更多的颜色、变化或交互功能。

posted @ 2024-12-30 09:50  王铁柱6  阅读(210)  评论(0)    收藏  举报