返回

烟花特效代码:用代码实现绚丽烟花特效,Canvas烟花模拟全解析

来源:网络   作者:   日期:2025-11-05 06:06:45  

烟花特效代码:用代码实现绚丽烟花特效,Canvas烟花模拟全解析

在数字世界中重现烟花绽放的璀璨瞬间,一直是前端开发者和创意技术爱好者的挑战之一,烟花的短暂与绚烂,为网页增添了节日氛围和视觉冲击力,本文将通过一个基于HTML5 Canvas的烟花特效代码示例,带您了解如何用代码实现逼真的烟花效果。

烟花特效代码:用代码实现绚丽烟花特效,Canvas烟花模拟全解析

核心代码实现

以下是完整的烟花特效代码,包含HTML结构和JavaScript实现:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">Canvas Fireworks</title>
    <style>
        body {
            margin: 0;
            overflow: hidden;
            background-color: #000;
        }
        canvas {
            display: block;
        }
    </style>
</head>
<body>
    <canvas id="canvas"></canvas>
    <script>
        // 获取Canvas元素和上下文
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        // 设置Canvas尺寸为窗口大小
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        // 烟花粒子数组
        let fireworks = [];
        let particles = [];
        // 烟花类
        class Firework {
            constructor(x, y, targetX, targetY) {
                this.x = x;
                this.y = y;
                this.targetX = targetX;
                this.targetY = targetY;
                this.speed = 2;
                this.angle = Math.atan2(targetY - y, targetX - x);
                this.velocity = {
                    x: Math.cos(this.angle) * this.speed,
                    y: Math.sin(this.angle) * this.speed
                };
                this.hue = Math.floor(Math.random() * 360);
                this.brightness = 50 + Math.random() * 50;
                this.particles = [];
            }
            // 更新烟花位置
            update() {
                this.x += this.velocity.x;
                this.y += this.velocity.y;
                // 检查是否到达目标位置
                const distanceToTarget = Math.sqrt(
                    Math.pow(this.targetX - this.x, 2) + 
                    Math.pow(this.targetY - this.y, 2)
                );
                if (distanceToTarget < 5) {
                    // 创建爆炸粒子
                    const result = this.createParticles();
                    if (result) {
                        // 烟花爆炸,移除自身
                        return true;
                    }
                }
                return false;
            }
            // 创建爆炸粒子
            createParticles() {
                const particleCount = 100;
                for (let i = 0; i < particleCount; i++) {
                    const angle = Math.random() * Math.PI * 2;
                    const speed = 2 + Math.random() * 3;
                    const vx = Math.cos(angle) * speed;
                    const vy = Math.sin(angle) * speed;
                    const size = 2 + Math.random() * 3;
                    const color = `hsl(${this.hue}, 100%, ${this.brightness}%)`;
                    particles.push(new Particle(this.x, this.y, vx, vy, size, color));
                }
                return true;
            }
            // 绘制烟花
            draw() {
                ctx.beginPath();
                ctx.arc(this.x, this.y, 3, 0, Math.PI * 2);
                ctx.fillStyle = `hsl(${this.hue}, 100%, 50%)`;
                ctx.fill();
            }
        }
        // 粒子类
        class Particle {
            constructor(x, y, vx, vy, size, color) {
                this.x = x;
                this.y = y;
                this.vx = vx;
                this.vy = vy;
                this.size = size;
                this.color = color;
                this.alpha = 1;
                this.friction = 0.98;
                this.gravity = 0.2;
                this.velocityDecay = 0.99;
            }
            // 更新粒子位置
            update() {
                this.x += this.vx;
                this.y += this.vy;
                this.vx *= this.friction;
                this.vy *= this.friction;
                this.vy += this.gravity;
                this.alpha -= 0.004;
                if (this.alpha <= 0) {
                    return false;
                }
                return true;
            }
            // 绘制粒子
            draw() {
                ctx.save();
                ctx.globalAlpha = this.alpha;
                ctx.fillStyle = this.color;
                ctx.beginPath();
                ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
                ctx.fill();
                ctx.restore();
            }
        }
        // 初始化烟花
        function initFirework() {
            const startX = Math.random() * canvas.width;
            const startY = canvas.height;
            const targetX = Math.random() * canvas.width;
            const targetY = Math.random() * canvas.height / 2;
            fireworks.push(new Firework(startX, startY, targetX, targetY));
        }
        // 动画循环
        function animate() {
            requestAnimationFrame(animate);
            ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            // 更新和绘制烟花
            for (let i = fireworks.length - 1; i >= 0; i--) {
                if (fireworks[i].update()) {
                    fireworks.splice(i, 1);
                } else {
                    fireworks[i].draw();
                }
            }
            // 更新和绘制粒子
            for (let i = particles.length - 1; i >= 0; i--) {
                if (!particles[i].update()) {
                    particles.splice(i, 1);
                } else {
                    particles[i].draw();
                }
            }
            // 随机生成新烟花
            if (Math.random() < 0.05) {
                initFirework();
            }
        }
        // 窗口大小调整处理
        window.addEventListener('resize', function() {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
        });
        // 点击生成烟花
        canvas.addEventListener('click', function(e) {
            const startX = e.clientX;
            const startY = e.clientY;
            const targetX = Math.random() * canvas.width;
            const targetY = Math.random() * canvas.height / 2;
            fireworks.push(new Firework(startX, startY, targetX, targetY));
        });
        // 开始动画
        animate();
    </script>
</body>
</html>

代码解析

这段代码实现了以下功能:

  1. 使用Canvas绘制烟花和粒子效果
  2. 烟花从底部发射,到达目标位置后爆炸
  3. 爆炸后产生多彩的粒子,带有重力效果和拖尾
  4. 粒子逐渐消失,模拟真实烟花效果
  5. 可通过点击页面任意位置发射烟花
  6. 自动随机生成烟花

技术要点

  • 使用Canvas API进行绘图
  • 实现了粒子系统,每个粒子都有独立的运动轨迹
  • 使用HSL颜色模式创建多彩效果
  • 添加了重力、摩擦力等物理效果
  • 通过requestAnimationFrame实现流畅动画

您可以根据需要调整参数,如粒子数量、颜色、速度等,来创建不同风格的烟花效果。

烟花特效代码:用代码实现绚丽烟花特效,Canvas烟花模拟全解析

分类:编程
责任编辑:今题网
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。

相关文章:

文章已关闭评论!