当前位置:首页 > 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实现拖拽功能需要监听鼠标事件,包括mousedown、mousemove和mouseup。以下是实现的基本逻辑: const draggableElem…

js实现vue

js实现vue

Vue.js 简介 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。其核心库专注于视图层,易于与其他库或现有项目整合。 实现 Vue.js 的基本步骤 安装 Vue.…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document…

js实现倒计时

js实现倒计时

使用 setInterval 实现倒计时 通过 setInterval 定时器每秒更新剩余时间,适用于简单倒计时场景。 function countdown(seconds, callbac…

js实现计算器

js实现计算器

实现基础计算器功能 使用JavaScript创建一个基础计算器需要处理数字输入、运算符逻辑和结果显示。以下是一个简单的实现示例: let currentInput = '0'; let previ…