返回

用Canvas画出缤纷烟火,照亮你的数字夜空

前端

用Canvas点亮夜空

烟火总是令人着迷的,它在黑暗中绽放,带来瞬间的光明和欢乐。如今,我们可以在数字世界中重现这一奇观,通过编程和Canvas元素,创造出属于自己的烟花盛宴。

绘画画布

第一步,我们需要创建一个HTML画布,它是我们烟花动画的舞台。我们可以使用HTML5的<canvas>元素来实现,如下所示:

<canvas id="canvas" width="800" height="600"></canvas>

接下来,我们需要在JavaScript中获取这个画布元素,并使用它的getContext()方法来获取一个绘图上下文,以便在画布上进行绘画。

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

构建粒子系统

烟花由许多小粒子组成,这些粒子会从发射点飞向不同的方向,并在到达最高点后坠落。为了模拟这种效果,我们需要创建一个粒子系统。

首先,我们需要定义一个Particle类来表示每个粒子。这个类应该包含粒子的位置、速度和颜色等属性。

class Particle {
  constructor(x, y, vx, vy, color) {
    this.x = x;
    this.y = y;
    this.vx = vx;
    this.vy = vy;
    this.color = color;
  }

  // 更新粒子状态
  update() {
    this.x += this.vx;
    this.y += this.vy;
    this.vy += 0.1; // 模拟重力
  }

  // 绘制粒子
  draw() {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, 2, 2);
  }
}

然后,我们需要创建一个ParticleSystem类来管理粒子系统。这个类负责创建粒子、更新粒子状态并绘制粒子。

class ParticleSystem {
  constructor() {
    this.particles = [];
  }

  // 创建粒子
  createParticle(x, y, vx, vy, color) {
    const particle = new Particle(x, y, vx, vy, color);
    this.particles.push(particle);
  }

  // 更新粒子状态
  update() {
    for (const particle of this.particles) {
      particle.update();
    }
  }

  // 绘制粒子
  draw() {
    for (const particle of this.particles) {
      particle.draw();
    }
  }
}

绘制烟花

现在,我们可以使用粒子系统来绘制烟花。首先,我们需要创建一个Firework类来表示单个烟花。这个类负责创建粒子并控制烟花的发射。

class Firework {
  constructor(x, y, color) {
    this.x = x;
    this.y = y;
    this.color = color;
    this.particleSystem = new ParticleSystem();
  }

  // 发射烟花
  launch() {
    for (let i = 0; i < 100; i++) {
      const vx = Math.random() * 2 - 1;
      const vy = Math.random() * -2;
      const color = this.color;
      this.particleSystem.createParticle(this.x, this.y, vx, vy, color);
    }
  }

  // 更新烟花状态
  update() {
    this.particleSystem.update();
  }

  // 绘制烟花
  draw() {
    this.particleSystem.draw();
  }
}

最后,我们需要创建一个FireworkSystem类来管理烟花系统。这个类负责创建烟花并控制烟花的发射。

class FireworkSystem {
  constructor() {
    this.fireworks = [];
  }

  // 创建烟花
  createFirework(x, y, color) {
    const firework = new Firework(x, y, color);
    this.fireworks.push(firework);
  }

  // 发射烟花
  launchFireworks() {
    for (const firework of this.fireworks) {
      firework.launch();
    }
  }

  // 更新烟花状态
  update() {
    for (const firework of this.fireworks) {
      firework.update();
    }
  }

  // 绘制烟花
  draw() {
    for (const firework of this.fireworks) {
      firework.draw();
    }
  }
}

动画循环

现在,我们已经构建好了烟花系统,接下来需要创建一个动画循环来不断更新和绘制烟花。我们可以使用requestAnimationFrame()函数来实现。

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布
  fireworkSystem.update();
  fireworkSystem.draw();
  requestAnimationFrame(animate);
}

animate();

结语

现在,您已经学会了如何使用Canvas元素和JavaScript来创建绚丽的烟花动画。您可以根据自己的喜好调整烟花的颜色、数量和发射速度,创造出独一无二的烟花盛宴。希望您能从本文中学到一些新的知识,并将其应用到自己的项目中。