利用JavaScript实现绘制2023新年烟花的示例代码

yizhihongxing

下面是在网页中利用JavaScript实现绘制2023新年烟花的完整攻略。

准备工作

在开始编写代码之前,我们需要准备以下工具和环境:

  • 一个文本编辑器,推荐使用 Visual Studio Code
  • 一个浏览器,推荐使用 Chrome
  • 一些基础的 JavaScript 知识,例如函数、变量、事件等

编写HTML结构

首先,我们需要在HTML文件中添加一个canvas标签,并设置宽高,代码如下:

<canvas id="fireworks"></canvas>

添加样式

为了让烟花能够在页面中居中并占据整个窗口,我们需要为 canvas 标签添加一些样式:

canvas {
  display: block;
  margin: auto;
}

编写 JavaScript 代码

接下来,我们就可以编写 JavaScript 代码来实现绘制烟花的功能了。

创建画布

我们需要创建一个画布,获取画布对象,并将其设置为全屏,并且设置画布的宽高为窗口的宽高,不过需要注意, HTML元素的宽高如果通过css设置,那么实际上元素的宽高仍旧是计算机能识别的默认值:

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

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

创建 Firework

创建一个 Firework 对象,用于描述烟花的基本属性,例如位置、颜色、运动轨迹等,代码如下:

class Firework {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
    this.target = {
      x: Math.random() * canvas.width,
      y: Math.random() * canvas.height
    }
    this.speed = 10;
    this.angle = Math.atan2(this.target.y - this.y, this.target.x - this.x);
    this.gravity = 0.2;
    this.vx = Math.cos(this.angle) * this.speed;
    this.vy = Math.sin(this.angle) * this.speed;
    this.opacity = 1;
    this.trail = [];
  }

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

    // Draw trail
    ctx.globalAlpha = this.opacity;
    for (let i = 0; i < this.trail.length; i++) {
      ctx.beginPath();
      ctx.arc(this.trail[i].x, this.trail[i].y, i * Math.random() * 2, 0, Math.PI * 2);
      ctx.fillStyle = this.color;
      ctx.fill();
    }
  }

  update() {
    // Update position
    this.x += this.vx;
    this.y += this.vy;

    // Update velocity
    this.vy += this.gravity;

    // Update opacity
    this.opacity -= 0.1;

    // Update trail
    this.trail.push({x: this.x, y: this.y});
    if (this.trail.length > 10) {
      this.trail.shift();
    }
  }
}

创建 Explosion

创建一个 Explosion 对象,用于描述烟花爆炸的基本属性,例如位置、颜色、大小等,代码如下:

class Explosion {
  constructor(x, y, color) {
    this.x = x;
    this.y = y;
    this.color = color;
    this.particles = [];

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

  draw() {
    for (let i = 0; i < this.particles.length; i++) {
      this.particles[i].draw();
    }
  }

  update() {
    for (let i = 0; i < this.particles.length; i++) {
      this.particles[i].update();
    }
  }
}

创建 Particle

创建一个 Particle 对象,用于描述烟花中的粒子,例如位置、大小、速度等,代码如下:

class Particle {
  constructor(x, y, color) {
    this.x = x;
    this.y = y;
    this.color = color;
    this.vx = Math.random() * 10 - 5;
    this.vy = Math.random() * 10 - 5;
    this.size = Math.random() * 3;
    this.gravity = 0.2;
    this.opacity = 1;
  }

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

  update() {
    this.x += this.vx;
    this.y += this.vy;
    this.vy += this.gravity;
    this.opacity -= 0.05;
    this.size -= 0.05;
  }
}

创建动画

现在,我们需要创建一个动画,用于在画布上不断绘制烟花,代码如下:

let fireworks = [];

function loop() {
  // Clear canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Draw fireworks
  for (let i = 0; i < fireworks.length; i++) {
    fireworks[i].draw();
    fireworks[i].update();

    // Explode when reach the target
    if (fireworks[i].y - fireworks[i].target.y > 0) {
      let explosion = new Explosion(fireworks[i].x, fireworks[i].y, fireworks[i].color);
      fireworks.splice(i, 1);
      i--;
      for (let j = 0; j < 10; j++) {
        fireworks.push(new Firework(explosion.x, explosion.y));
      }
    }
  }

  // Generate new firework
  if (Math.random() < 0.2) {
    fireworks.push(new Firework(canvas.width/2, canvas.height));
  }

  requestAnimationFrame(loop);
}

loop();

完整代码

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>2023 New Year Fireworks</title>
  <style>
    canvas {
      display: block;
      margin: auto;
    }
  </style>
</head>
<body>
  <canvas id="fireworks"></canvas>
  <script>
    const canvas = document.getElementById('fireworks');
    const ctx = canvas.getContext('2d');

    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    class Firework {
      constructor(x, y) {
        this.x = x;
        this.y = y;
        this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
        this.target = {
          x: Math.random() * canvas.width,
          y: Math.random() * canvas.height
        }
        this.speed = 10;
        this.angle = Math.atan2(this.target.y - this.y, this.target.x - this.x);
        this.gravity = 0.2;
        this.vx = Math.cos(this.angle) * this.speed;
        this.vy = Math.sin(this.angle) * this.speed;
        this.opacity = 1;
        this.trail = [];
      }

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

        // Draw trail
        ctx.globalAlpha = this.opacity;
        for (let i = 0; i < this.trail.length; i++) {
          ctx.beginPath();
          ctx.arc(this.trail[i].x, this.trail[i].y, i * Math.random() * 2, 0, Math.PI * 2);
          ctx.fillStyle = this.color;
          ctx.fill();
        }
      }

      update() {
        // Update position
        this.x += this.vx;
        this.y += this.vy;

        // Update velocity
        this.vy += this.gravity;

        // Update opacity
        this.opacity -= 0.1;

        // Update trail
        this.trail.push({x: this.x, y: this.y});
        if (this.trail.length > 10) {
          this.trail.shift();
        }
      }
    }

    class Explosion {
      constructor(x, y, color) {
        this.x = x;
        this.y = y;
        this.color = color;
        this.particles = [];

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

      draw() {
        for (let i = 0; i < this.particles.length; i++) {
          this.particles[i].draw();
        }
      }

      update() {
        for (let i = 0; i < this.particles.length; i++) {
          this.particles[i].update();
        }
      }
    }

    class Particle {
      constructor(x, y, color) {
        this.x = x;
        this.y = y;
        this.color = color;
        this.vx = Math.random() * 10 - 5;
        this.vy = Math.random() * 10 - 5;
        this.size = Math.random() * 3;
        this.gravity = 0.2;
        this.opacity = 1;
      }

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

      update() {
        this.x += this.vx;
        this.y += this.vy;
        this.vy += this.gravity;
        this.opacity -= 0.05;
        this.size -= 0.05;
      }
    }

    let fireworks = [];

    function loop() {
      // Clear canvas
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // Draw fireworks
      for (let i = 0; i < fireworks.length; i++) {
        fireworks[i].draw();
        fireworks[i].update();

        // Explode when reach the target
        if (fireworks[i].y - fireworks[i].target.y > 0) {
          let explosion = new Explosion(fireworks[i].x, fireworks[i].y, fireworks[i].color);
          fireworks.splice(i, 1);
          i--;
          for (let j = 0; j < 10; j++) {
            fireworks.push(new Firework(explosion.x, explosion.y));
          }
        }
      }

      // Generate new firework
      if (Math.random() < 0.2) {
        fireworks.push(new Firework(canvas.width/2, canvas.height));
      }

      requestAnimationFrame(loop);
    }

    loop();
  </script>
</body>
</html>

这样,当我们在浏览器中打开该 HTML 文件时,就能看到一个基于 JavaScript 实现的烟花动画效果了。

示例说明

  1. 修改烟花绘制的速度:将代码中的 speed 值调大或调小即可,例如将 speed 调整为 5,表示烟花的速度变慢了,可以让动画变得更加缓慢。

  2. 修改烟花交互方式:在 Demo 中实现的是以随机方式自动弹出一些烟火, 如果希望增加交互性,可以在页面上添加按钮等交互元素,当用户点击按钮时,触发 JavaScript 代码,从而实现相应的动画效果。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:利用JavaScript实现绘制2023新年烟花的示例代码 - Python技术站

(0)
上一篇 2023年6月11日
下一篇 2023年6月11日

相关文章

  • 弱类型语言javascript中 a,b 的运算实例小结

    为了理解“弱类型语言javascript中 a,b 的运算实例”,需先了解JS的数据类型。 JS的7种数据类型分为两种类型:原始类型和引用类型。- 原始类型:数字(Number)、字符串(String)、布尔(Boolean)、null、undefined、Symbol- 引用类型:对象(Object)、数组(Array)、函数(Function) JS中的…

    JavaScript 2023年6月10日
    00
  • vue quill editor 使用富文本添加上传音频功能

    下面为您讲解vue quill editor 如何添加富文本上传音频功能的攻略: 1. 安装依赖 首先需要安装vue-quill-editor和quill-image-extend-module的依赖,使用npm命令如下: npm install vue-quill-editor quill-image-extend-module 2. 引入依赖 在需要实现…

    JavaScript 2023年6月11日
    00
  • 使用RequireJS库加载JavaScript模块的实例教程

    我来详细讲解如何使用RequireJS库加载JavaScript模块。 什么是RequireJS RequireJS是一个JavaScript模块加载器,它可以帮助我们实现依赖模块的异步加载。它采用了AMD规范,并提供了一种便捷的方式,使JavaScript开发人员可以更容易地组织和管理代码。 安装与配置 下载RequireJS 去RequireJS的官方网…

    JavaScript 2023年5月27日
    00
  • JS中轻松遍历对象属性的几种方式

    关闭符合MD格式的字体 JS中轻松遍历对象属性的几种方式 JS中的对象是一种非常重要的数据类型,有时候我们需要遍历对象的所有属性以进行操作。下面是几种轻松遍历对象属性的方式: 方式1:for…in循环遍历对象 for…in是一种常见的遍历对象属性的方法。它可以遍历对象上的所有属性,可以处理对象本身定义的属性,还可以处理从Object.prototyp…

    JavaScript 2023年5月27日
    00
  • 如何在JavaScript中谨慎使用代码注释

    如何在JavaScript中谨慎使用代码注释 为什么需要谨慎使用代码注释 代码注释是一种注释性的文本,用于解释代码的含义、目的、用途、算法、实现方式等,通常用于提高代码的可读性和可维护性。但是在实际编程过程中,过量和不恰当的代码注释可能会导致以下影响: 代码冗余: 如果代码本身已经清晰易懂,但还增加了很多无用的注释,则会浪费磁盘空间和带宽。 注释过时: 如果…

    JavaScript 2023年5月27日
    00
  • 记录-js基础练习题

    这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助 隔行换色(%): window.onload = function() { var aLi = document.getElementsByTagName(‘li’); for(var i = 0; i < aLi.length; i++){ if(i%2 == 1){ aLi[i].sty…

    JavaScript 2023年4月18日
    00
  • Jquery cookie操作代码

    当涉及到网站开发时,处理用户的Cookie数据变得非常重要。Jquery框架提供了方便的方法来处理Cookies。 以下是几个可以使用jQuery对cookie进行操作的方法: 设置Cookie 设置cookie有以下几个参数: $.cookie(‘cookieName’, ‘cookieValue’, { expires: 7, path: ‘/’ });…

    JavaScript 2023年6月11日
    00
  • HTML5 History API 实现无刷新跳转

    HTML5 History API 是HTML5新增的一个API,通过该API可以更好地管理浏览器的历史记录和URL,实现无刷新跳转。 下面是HTML5 History API 实现无刷新跳转的具体步骤: 步骤一:改变URL,更新浏览器历史记录 使用HTML5 History API,可以通过调用window.history.pushState()方法来改变…

    JavaScript 2023年6月11日
    00
合作推广
合作推广
分享本页
返回顶部