html烟花ヾ(≧▽≦*)o

以下是一个简单的可以放烟花的网站代码示例,将以下代码保存为 index.html  文件,在浏览器中打开即可看到烟花效果:

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>动态放烟花</title>
  <style>
    body {
      margin: 0;
      padding: 0;
    }

    canvas {
      display: block;
      position: absolute;
      top: 0;
      left: 0;
      z-index: -1;
    }
  </style>
</head>

<body>
  <canvas id="myCanvas"></canvas>
  <script>
    // 获取canvas元素和上下文
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");

    // 设置canvas大小和背景颜色
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    ctx.fillStyle = "#000";
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 创建烟花类
    function Firework() {
      this.x = Math.random() * canvas.width; // 烟花的x坐标
      this.y = canvas.height; // 烟花的y坐标
      this.color = `hsl(${Math.floor(Math.random() * 360)}, 100%, 50%)`; // 烟花颜色
      this.radius = 2; // 烟花半径
      this.velocity = { // 烟花速度
        x: Math.random() * 6 - 3,
        y: Math.random() * -15 - 10
      };
      this.gravity = 0.2; // 烟花重力
      this.opacity = 1; // 烟花透明度
      this.trail = []; // 烟花粒子轨迹
    }

    // 更新烟花位置
    Firework.prototype.update = function () {
      this.x += this.velocity.x;
      this.velocity.y += this.gravity;
      this.y += this.velocity.y;
      this.opacity -= 0.02;

      // 更新烟花粒子轨迹
      this.trail.push({ x: this.x, y: this.y });

      // 删除不需要的烟花粒子
      if (this.trail.length > 15) {
        this.trail.shift();
      }
    }

    // 绘制烟花
    Firework.prototype.draw = function () {
      ctx.globalAlpha = this.opacity;
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
      ctx.fillStyle = this.color;
      ctx.fill();

      // 绘制烟花粒子轨迹
      for (var i = 0; i < this.trail.length; i++) {
        ctx.fillStyle = this.color;
        ctx.fillRect(this.trail[i].x, this.trail[i].y, this.radius, this.radius);
      }
    }

    // 创建烟花数组
    var fireworks = [];

    // 循环绘制烟花
    function loop() {
      setTimeout(function () {
        requestAnimationFrame(loop);
        ctx.fillStyle = "rgba(0, 0, 0, 0.05)";
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // 随机生成烟花
        if (Math.random() < 0.03) {
          fireworks.push(new Firework());
        }

        // 更新和绘制每个烟花
        for (var i = 0; i < fireworks.length; i++) {
          fireworks[i].update();
          fireworks[i].draw();

          // 删除已经消失的烟花
          if (fireworks[i].opacity <= 0) {
            fireworks.splice(i, 1);
          }
        }
      }, 1000 / 60);
    }

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

</html>

这段代码使用了HTML5的 <canvas>  元素和JavaScript来实现烟花效果,通过不断地随机生成烟花、更新烟花的位置和绘制烟花,以及处理烟花粒子的轨迹和透明度等,营造出了动态的烟花绽放效果,提前祝粉丝们新年快乐!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值