当前位置:首页 > JavaScript

用js实现烟花

2026-02-02 18:24:57JavaScript

实现烟花效果的JavaScript代码

以下是一个使用HTML5 Canvas和JavaScript实现烟花效果的完整示例:

// 获取Canvas元素和上下文
const canvas = document.getElementById('fireworksCanvas');
const ctx = canvas.getContext('2d');

// 设置Canvas尺寸为窗口大小
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

// 烟花粒子类
class Particle {
  constructor(x, y, color) {
    this.x = x;
    this.y = y;
    this.color = color;
    this.velocity = {
      x: (Math.random() - 0.5) * 8,
      y: (Math.random() - 0.5) * 8
    };
    this.alpha = 1;
    this.decay = Math.random() * 0.015 + 0.01;
    this.size = Math.random() * 3 + 1;
  }

  update() {
    this.velocity.y += 0.05; // 重力效果
    this.x += this.velocity.x;
    this.y += this.velocity.y;
    this.alpha -= this.decay;
  }

  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.closePath();
    ctx.fill();
    ctx.restore();
  }
}

// 烟花类
class Firework {
  constructor(x, y, targetX, targetY, color) {
    this.x = x;
    this.y = y;
    this.targetX = targetX;
    this.targetY = targetY;
    this.color = color;
    this.particles = [];
    this.speed = 3;
    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.exploded = false;
  }

  update() {
    if (!this.exploded) {
      this.x += this.velocity.x;
      this.y += this.velocity.y;

      const distance = Math.hypot(this.targetX - this.x, this.targetY - this.y);
      if (distance < 5) {
        this.explode();
      }
    }

    for (let i = this.particles.length - 1; i >= 0; i--) {
      this.particles[i].update();
      if (this.particles[i].alpha <= 0) {
        this.particles.splice(i, 1);
      }
    }
  }

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

  draw() {
    if (!this.exploded) {
      ctx.beginPath();
      ctx.arc(this.x, this.y, 2, 0, Math.PI * 2);
      ctx.fillStyle = this.color;
      ctx.fill();
    }

    for (const particle of this.particles) {
      particle.draw();
    }
  }
}

// 烟花数组
const fireworks = [];

// 随机颜色生成
function getRandomColor() {
  const hue = Math.floor(Math.random() * 360);
  return `hsl(${hue}, 100%, 50%)`;
}

// 动画循环
function animate() {
  requestAnimationFrame(animate);
  ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // 随机生成新烟花
  if (Math.random() < 0.03) {
    const x = Math.random() * canvas.width;
    const y = canvas.height;
    const targetX = Math.random() * canvas.width;
    const targetY = Math.random() * canvas.height * 0.6;
    const color = getRandomColor();
    fireworks.push(new Firework(x, y, targetX, targetY, color));
  }

  for (let i = fireworks.length - 1; i >= 0; i--) {
    fireworks[i].update();
    fireworks[i].draw();
    if (fireworks[i].exploded && fireworks[i].particles.length === 0) {
      fireworks.splice(i, 1);
    }
  }
}

// 启动动画
animate();

// 窗口大小调整时重设Canvas尺寸
window.addEventListener('resize', () => {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
});

HTML部分

需要在HTML中添加一个Canvas元素:

用js实现烟花

<!DOCTYPE html>
<html>
<head>
    <title>烟花效果</title>
    <style>
        body {
            margin: 0;
            overflow: hidden;
            background: #000;
        }
        canvas {
            display: block;
        }
    </style>
</head>
<body>
    <canvas id="fireworksCanvas"></canvas>
    <script src="fireworks.js"></script>
</body>
</html>

实现原理

烟花效果通过Canvas绘制实现,主要分为两部分:

用js实现烟花

  • 上升阶段的烟花(Firework类)
  • 爆炸后的粒子效果(Particle类)

每个烟花从屏幕底部随机位置发射,飞向随机目标位置后爆炸,生成大量彩色粒子。粒子受到重力影响逐渐下落,同时透明度逐渐降低直至消失。

自定义选项

可以通过修改以下参数调整效果:

  • 粒子数量:修改explode()方法中的循环次数
  • 重力大小:调整Particle类中this.velocity.y += 0.05的值
  • 烟花发射频率:修改animate()函数中的Math.random() < 0.03阈值
  • 颜色模式:修改getRandomColor()函数使用不同颜色生成逻辑

这个实现提供了基础的烟花效果,可以根据需要进一步扩展,如添加声音效果、不同类型的爆炸图案或交互功能。

标签: 烟花js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。 // 方…

js实现分页

js实现分页

分页的基本实现思路 在JavaScript中实现分页功能通常需要结合前端和后端逻辑。前端负责渲染分页控件和处理用户交互,后端负责提供分页数据。 前端分页实现 纯前端分页适用于数据量较小的情况,可以直…

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('image…

js实现自举

js实现自举

实现 JavaScript 自举的方法 JavaScript 自举(Bootstrap)通常指通过 JavaScript 动态加载自身或依赖的脚本,实现运行时环境的初始化或扩展。以下是几种常见实现方式…

js实现目录

js实现目录

实现目录的基本思路 在JavaScript中实现目录功能通常涉及以下几个核心步骤:解析文档中的标题元素(如h1-h6),动态生成目录结构,并添加交互逻辑(如点击跳转)。以下是具体实现方法: 解析标题…

js实现密码

js实现密码

密码强度验证 使用正则表达式验证密码强度是一种常见方法。以下代码检查密码是否包含大小写字母、数字和特殊字符,且长度至少为8位: function checkPasswordStrength(pass…