firework666edit icon

创建者:
邓朝元
Fork(复制)
下载
嵌入
BUG反馈
index.html
index.html
            
            <!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>🎆 Fantastic Fireworks Studio</title>
  <style>
    :root {
      --ui-bg: rgba(15, 18, 40, .72);
      --ui-border: rgba(255, 255, 255, .14);
      --accent: #ffd166;
      --text: #f1f3ff;
    }

    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }

    html,
    body {
      height: 100%;
      overflow: hidden;
      font-family: "Segoe UI", system-ui, sans-serif;
    }

    body {
      background: #04060f;
      color: var(--text);
    }

    canvas#sky {
      position: fixed;
      inset: 0;
      display: block;
      cursor: crosshair;
    }

    #panel {
      position: fixed;
      top: 14px;
      left: 14px;
      z-index: 10;
      width: 300px;
      max-height: calc(100vh - 28px);
      overflow-y: auto;
      background: var(--ui-bg);
      border: 1px solid var(--ui-border);
      border-radius: 16px;
      backdrop-filter: blur(10px);
      box-shadow: 0 10px 40px rgba(0, 0, 0, .5);
      padding: 16px;
      transition: transform .35s ease, opacity .35s ease;
    }

    #panel.hidden {
      transform: translateX(-115%);
      opacity: 0;
      pointer-events: none;
    }

    #panel h1 {
      font-size: 17px;
      letter-spacing: .5px;
      margin-bottom: 4px;
      background: linear-gradient(90deg, #ff6b6b, #ffd166, #4ecdc4, #a78bfa);
      -webkit-background-clip: text;
      background-clip: text;
      color: transparent;
    }

    #panel .sub {
      font-size: 11px;
      opacity: .65;
      margin-bottom: 12px;
    }

    fieldset {
      border: 1px solid var(--ui-border);
      border-radius: 10px;
      padding: 10px;
      margin-bottom: 12px;
    }

    legend {
      font-size: 11px;
      text-transform: uppercase;
      letter-spacing: 1.2px;
      opacity: .75;
      padding: 0 6px;
    }

    .row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 8px;
      margin: 7px 0;
      font-size: 12.5px;
    }

    .row label {
      flex: 1;
      opacity: .9;
    }

    .row output {
      min-width: 34px;
      text-align: right;
      font-variant-numeric: tabular-nums;
      opacity: .8;
      font-size: 11px;
    }

    input[type="range"] {
      width: 120px;
      accent-color: var(--accent);
    }

    select {
      background: #1b2140;
      color: var(--text);
      border: 1px solid var(--ui-border);
      border-radius: 8px;
      padding: 5px 8px;
      font-size: 12px;
      width: 150px;
    }

    .btn-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 8px;
      margin-top: 6px;
    }

    button {
      cursor: pointer;
      border: 1px solid var(--ui-border);
      border-radius: 9px;
      padding: 8px 10px;
      font-size: 12.5px;
      color: var(--text);
      background: linear-gradient(180deg, #2a3160, #1a1f3d);
      transition: filter .15s, transform .1s;
    }

    button:hover {
      filter: brightness(1.3);
    }

    button:active {
      transform: scale(.96);
    }

    button.primary {
      background: linear-gradient(180deg, #c94f7c, #8e2f5b);
      border-color: #e58ab5;
    }

    button.ghost {
      background: transparent;
    }

    .toggle {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 12.5px;
      margin: 6px 0;
      cursor: pointer;
      user-select: none;
    }

    .toggle input {
      accent-color: var(--accent);
      width: 15px;
      height: 15px;
      cursor: pointer;
    }

    kbd {
      background: #232a4d;
      border: 1px solid var(--ui-border);
      border-bottom-width: 2px;
      border-radius: 5px;
      padding: 1px 6px;
      font-size: 10.5px;
      font-family: monospace;
    }

    #helpBox {
      font-size: 11px;
      line-height: 1.9;
      opacity: .8;
    }

    #panelToggle {
      position: fixed;
      top: 14px;
      left: 14px;
      z-index: 11;
      width: 42px;
      height: 42px;
      border-radius: 50%;
      font-size: 19px;
      display: none;
      align-items: center;
      justify-content: center;
      background: var(--ui-bg);
      backdrop-filter: blur(8px);
    }

    #panelToggle.show {
      display: flex;
    }

    #hud {
      position: fixed;
      right: 14px;
      top: 14px;
      z-index: 10;
      background: var(--ui-bg);
      border: 1px solid var(--ui-border);
      border-radius: 12px;
      padding: 8px 14px;
      font-size: 11.5px;
      backdrop-filter: blur(8px);
      text-align: right;
      line-height: 1.6;
      font-variant-numeric: tabular-nums;
    }

    #themeName {
      position: fixed;
      bottom: 20px;
      left: 50%;
      transform: translateX(-50%);
      z-index: 10;
      font-size: 26px;
      font-weight: 700;
      letter-spacing: 3px;
      text-transform: uppercase;
      pointer-events: none;
      opacity: 0;
      text-shadow: 0 0 18px rgba(255, 255, 255, .6);
    }

    #themeName.pop {
      animation: pop 2.2s ease forwards;
    }

    @keyframes pop {
      0% {
        opacity: 0;
        transform: translateX(-50%) scale(.7);
      }

      15% {
        opacity: 1;
        transform: translateX(-50%) scale(1.05);
      }

      75% {
        opacity: 1;
      }

      100% {
        opacity: 0;
        transform: translateX(-50%) scale(1.1);
      }
    }

    ::-webkit-scrollbar {
      width: 7px;
    }

    ::-webkit-scrollbar-thumb {
      background: #3a4270;
      border-radius: 4px;
    }
  </style>
</head>

<body>
  <canvas id="sky"></canvas>
  <button id="panelToggle" title="Show controls (H)">⚙️</button>

  <div id="panel">
    <h1>🎆 Fantastic Fireworks Studio</h1>
    <div class="sub">Click / drag the sky to launch • Double-click for a mega burst</div>

    <fieldset>
      <legend>Theme</legend>
      <div class="row"><label for="theme">Palette &amp; style</label>
        <select id="theme">
          <option value="classic">Classic Gala</option>
          <option value="neon">Neon Cyberpunk</option>
          <option value="pastel">Pastel Dream</option>
          <option value="golden">Golden Royal</option>
          <option value="galaxy">Galaxy / Aurora</option>
          <option value="fire">Inferno</option>
          <option value="ocean">Ocean Breeze</option>
          <option value="rainbow">Rainbow Riot</option>
        </select>
      </div>
      <label class="toggle"><input type="checkbox" id="autoCycle"> Auto-cycle themes every 20s</label>
    </fieldset>

    <fieldset>
      <legend>Shell Type</legend>
      <div class="row"><label for="shell">Burst pattern</label>
        <select id="shell">
          <option value="random">🎲 Random</option>
          <option value="peony">Peony (sphere)</option>
          <option value="chrysanthemum">Chrysanthemum (trails)</option>
          <option value="willow">Willow (drooping)</option>
          <option value="ring">Ring</option>
          <option value="heart">Heart 💖</option>
          <option value="star">Star ⭐</option>
          <option value="double">Double Shell</option>
          <option value="palm">Palm</option>
          <option value="crackle">Crackle / Glitter</option>
          <option value="fisheye">Fish-Eye</option>
          <option value="v">V-Burst</option>
        </select>
      </div>
    </fieldset>

    <fieldset>
      <legend>Physics &amp; Look</legend>
      <div class="row"><label>Gravity</label><input type="range" id="gravity" min="0" max="0.3" step="0.01" value="0.08"><output id="gravityOut">0.08</output></div>
      <div class="row"><label>Wind X</label><input type="range" id="wind" min="-0.15" max="0.15" step="0.01" value="0"><output id="windOut">0.00</output></div>
      <div class="row"><label>Explosion size</label><input type="range" id="power" min="4" max="16" step="0.5" value="9"><output id="powerOut">9</output></div>
      <div class="row"><label>Particle count</label><input type="range" id="count" min="30" max="400" step="10" value="140"><output id="countOut">140</output></div>
      <div class="row"><label>Trail length</label><input type="range" id="fade" min="0.02" max="0.4" step="0.01" value="0.08"><output id="fadeOut">0.08</output></div>
    </fieldset>

    <fieldset>
      <legend>Automation</legend>
      <div class="row"><label>Auto-launch rate</label><input type="range" id="autoRate" min="0" max="10" step="0.5" value="0"><output id="autoRateOut">off</output></div>
      <label class="toggle"><input type="checkbox" id="showStars" checked> Show starfield background</label>
      <label class="toggle"><input type="checkbox" id="glow" checked> Bloom / glow effects</label>
      <label class="toggle"><input type="checkbox" id="sound"> Sound FX (synthesized booms)</label>
      <div class="btn-grid">
        <button id="finaleBtn" class="primary">🎇 GRAND FINALE</button>
        <button id="clearBtn" class="ghost">🧹 Clear Sky</button>
      </div>
    </fieldset>

    <fieldset>
      <legend>Help</legend>
      <div id="helpBox">
        <kbd>Click</kbd> launch &nbsp; <kbd>Dbl-click</kbd> mega burst<br>
        <kbd>Space</kbd> random launch &nbsp; <kbd>F</kbd> finale<br>
        <kbd>T</kbd> next theme &nbsp; <kbd>H</kbd> hide panel<br>
        <kbd>C</kbd> clear &nbsp; <kbd>S</kbd> toggle sound
      </div>
    </fieldset>
  </div>

  <div id="hud">FPS <span id="fps">60</span><br>Particles <span id="pcount">0</span></div>
  <div id="themeName"></div>

  <script>
    "use strict";
    const canvas = document.getElementById('sky'),
      ctx = canvas.getContext('2d');
    let W, H, DPR;

    function resize() {
      DPR = Math.min(window.devicePixelRatio || 1, 2);
      W = window.innerWidth;
      H = window.innerHeight;
      canvas.width = W * DPR;
      canvas.height = H * DPR;
      canvas.style.width = W + 'px';
      canvas.style.height = H + 'px';
      ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
      buildStars();
    }
    window.addEventListener('resize', resize);
    /* -------- THEMES -------- */
    const THEMES = {
      classic: {
        hues: [0, 45, 120, 200, 280, 330],
        sat: 100,
        bri: 100,
        bg: '#04060f',
        trailHueShift: 0,
        sparkle: .25,
        name: 'Classic Gala'
      },
      neon: {
        hues: [185, 300, 120, 265, 320],
        sat: 100,
        bri: 100,
        bg: '#050014',
        trailHueShift: 60,
        sparkle: .15,
        name: 'Neon Cyberpunk'
      },
      pastel: {
        hues: [340, 20, 55, 150, 200, 265],
        sat: 70,
        bri: 100,
        bg: '#0a0a18',
        trailHueShift: 0,
        sparkle: .1,
        name: 'Pastel Dream'
      },
      golden: {
        hues: [38, 48, 55, 30, 42],
        sat: 95,
        bri: 100,
        bg: '#0b0703',
        trailHueShift: -8,
        sparkle: .5,
        name: 'Golden Royal'
      },
      galaxy: {
        hues: [260, 200, 280, 170, 310],
        sat: 85,
        bri: 100,
        bg: '#020210',
        trailHueShift: 40,
        sparkle: .6,
        name: 'Galaxy Aurora'
      },
      fire: {
        hues: [5, 15, 25, 35, 45, 8],
        sat: 100,
        bri: 100,
        bg: '#0d0300',
        trailHueShift: -10,
        sparkle: .35,
        name: 'Inferno'
      },
      ocean: {
        hues: [180, 200, 220, 160, 190],
        sat: 90,
        bri: 95,
        bg: '#010a12',
        trailHueShift: 25,
        sparkle: .2,
        name: 'Ocean Breeze'
      },
      rainbow: {
        hues: null,
        sat: 100,
        bri: 100,
        bg: '#060608',
        trailHueShift: 0,
        sparkle: .3,
        name: 'Rainbow Riot'
      },
    };
    let themeKey = 'classic';
    const theme = () => THEMES[themeKey];

    function randHue() {
      const t = theme();
      if (!t.hues) return Math.random() * 360;
      return (t.hues[(Math.random() * t.hues.length) | 0] + (Math.random() * 40 - 20) + 360) % 360;
    }
    const S = {
      gravity: .08,
      wind: 0,
      power: 9,
      count: 140,
      fade: .08,
      autoRate: 0,
      showStars: true,
      glow: true,
      sound: false,
      shell: 'random',
      autoCycle: false
    };
    const rockets = [],
      particles = [],
      sparks = [];
    let flashAlpha = 0;
    /* -------- STARFIELD -------- */
    let stars = [];

    function buildStars() {
      stars = [];
      const n = Math.floor((W * H) / 6000);
      for (let i = 0; i < n; i++) stars.push({
        x: Math.random() * W,
        y: Math.random() * H * .9,
        r: Math.random() * 1.3 + .2,
        tw: Math.random() * Math.PI * 2,
        sp: .5 + Math.random() * 2
      });
    }
    /* -------- SYNTH AUDIO -------- */
    let AC = null;

    function audioCtx() {
      if (!AC) {
        try {
          AC = new(window.AudioContext || window.webkitAudioContext)();
        } catch (e) {}
      }
      return AC;
    }

    function boom(size = 1) {
      if (!S.sound) return;
      const ac = audioCtx();
      if (!ac) return;
      const dur = .6 * size,
        buf = ac.createBuffer(1, ac.sampleRate * dur, ac.sampleRate),
        d = buf.getChannelData(0);
      for (let i = 0; i < d.length; i++) {
        const t = i / d.length;
        d[i] = (Math.random() * 2 - 1) * Math.pow(1 - t, 2.5);
      }
      const src = ac.createBufferSource();
      src.buffer = buf;
      const lp = ac.createBiquadFilter();
      lp.type = 'lowpass';
      lp.frequency.setValueAtTime(900 * size, ac.currentTime);
      lp.frequency.exponentialRampToValueAtTime(80, ac.currentTime + dur);
      const g = ac.createGain();
      g.gain.value = Math.min(.5, .22 * size);
      src.connect(lp).connect(g).connect(ac.destination);
      src.start();
    }

    function crackleSound() {
      if (!S.sound) return;
      const ac = audioCtx();
      if (!ac) return;
      const dur = .5,
        buf = ac.createBuffer(1, ac.sampleRate * dur, ac.sampleRate),
        d = buf.getChannelData(0);
      for (let i = 0; i < d.length; i++) d[i] = (Math.random() < .03 ? (Math.random() * 2 - 1) : 0) * (1 - i / d.length);
      const src = ac.createBufferSource();
      src.buffer = buf;
      const hp = ac.createBiquadFilter();
      hp.type = 'highpass';
      hp.frequency.value = 2000;
      const g = ac.createGain();
      g.gain.value = .25;
      src.connect(hp).connect(g).connect(ac.destination);
      src.start();
    }
    const rand = (a, b) => a + Math.random() * (b - a);
    const hsla = (h, s, l, a) => `hsla(${h},${s}%,${l}%,${a})`;
    /* -------- ROCKET -------- */
    class Rocket {
      constructor(tx, ty, shellOverride) {
        this.x = rand(W * .15, W * .85);
        this.y = H;
        this.tx = tx;
        this.ty = ty;
        const ang = Math.atan2(ty - this.y, tx - this.x),
          dist = Math.hypot(tx - this.x, ty - this.y);
        this.speed = Math.sqrt(2 * S.gravity * dist) * rand(1.02, 1.15);
        this.vx = Math.cos(ang) * this.speed;
        this.vy = Math.sin(ang) * this.speed;
        this.hue = randHue();
        this.trail = [];
        this.dead = false;
        this.shell = shellOverride || (S.shell === 'random' ?
          ['peony', 'chrysanthemum', 'willow', 'ring', 'heart', 'star', 'double', 'palm', 'crackle', 'fisheye', 'v'][(Math.random() * 11) | 0] :
          S.shell);
      }
      update() {
        this.trail.push({
          x: this.x,
          y: this.y
        });
        if (this.trail.length > 8) this.trail.shift();
        this.vy += S.gravity * .45;
        this.vx += S.wind * .3;
        this.x += this.vx;
        this.y += this.vy;
        if (this.vy >= -0.6 || this.y <= this.ty) {
          this.dead = true;
          explode(this.x, this.y, this.hue, this.shell, this.shell === 'double' ? 1 : undefined);
        }
      }
      draw() {
        ctx.save();
        if (S.glow) {
          ctx.shadowBlur = 12;
          ctx.shadowColor = hsla(this.hue, 100, 70, 1);
        }
        for (let i = 0; i < this.trail.length; i++) {
          const p = this.trail[i],
            a = i / this.trail.length;
          ctx.fillStyle = hsla(this.hue, 90, 60 + 20 * a, a * .8);
          ctx.beginPath();
          ctx.arc(p.x, p.y, 1.6 * a + .6, 0, 7);
          ctx.fill();
        }
        ctx.fillStyle = hsla(this.hue, 100, 85, 1);
        ctx.beginPath();
        ctx.arc(this.x, this.y, 2.6, 0, 7);
        ctx.fill();
        ctx.restore();
      }
    }
    /* -------- PARTICLE -------- */
    class Particle {
      constructor(x, y, vx, vy, hue, opts = {}) {
        this.x = x;
        this.y = y;
        this.vx = vx;
        this.vy = vy;
        this.hue = hue;
        this.sat = theme().sat;
        this.life = opts.life ?? rand(60, 110);
        this.maxLife = this.life;
        this.decay = opts.decay ?? rand(.9, 1);
        this.friction = opts.friction ?? .985;
        this.gravMul = opts.gravMul ?? 1;
        this.size = opts.size ?? rand(1.2, 2.4);
        this.trail = opts.trail ?? false;
        this.trailPts = [];
        this.sparkle = Math.random() < (opts.sparkle ?? theme().sparkle);
        this.crackle = opts.crackle || false;
        this.flickerPhase = Math.random() * Math.PI * 2;
        this.dead = false;
      }
      update() {
        if (this.trail) {
          this.trailPts.push({
            x: this.x,
            y: this.y
          });
          if (this.trailPts.length > 6) this.trailPts.shift();
        }
        this.vx *= this.friction;
        this.vy *= this.friction;
        this.vy += S.gravity * this.gravMul;
        this.vx += S.wind;
        this.x += this.vx;
        this.y += this.vy;
        this.life -= this.decay;
        if (this.crackle && this.life > 0 && Math.random() < .02)
          sparks.push(new Particle(this.x, this.y, rand(-.4, .4), rand(-.4, .4), (this.hue + rand(-20, 20) + 360) % 360, {
            life: rand(8, 20),
            size: rand(.6, 1.4),
            gravMul: .3
          }));
        if (this.life <= 0) this.dead = true;
      }
      draw() {
        const t = this.life / this.maxLife;
        let alpha = t < .35 ? t / .35 : 1;
        if (this.sparkle) alpha *= (.4 + .6 * Math.abs(Math.sin(this.flickerPhase + performance.now() * .02)));
        const bright = 45 + 45 * t;
        if (this.trail && this.trailPts.length > 1) {
          ctx.strokeStyle = hsla(this.hue, this.sat, bright * .8, alpha * .5);
          ctx.lineWidth = this.size * .8;
          ctx.beginPath();
          ctx.moveTo(this.trailPts[0].x, this.trailPts[0].y);
          for (const p of this.trailPts) ctx.lineTo(p.x, p.y);
          ctx.lineTo(this.x, this.y);
          ctx.stroke();
        }
        ctx.fillStyle = hsla(this.hue, this.sat, bright, alpha);
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size * (.5 + .5 * t), 0, 7);
        ctx.fill();
      }
    }
    /* -------- SHELL PATTERNS -------- */
    function makeShell(kind, cx, cy, hue, scale) {
      const N = Math.round(S.count * (scale || 1)),
        P = S.power;
      const add = (vx, vy, o = {}) => particles.push(new Particle(cx, cy, vx, vy, (hue + (o.dh || 0) + 360) % 360, o));
      switch (kind) {
      case 'peony':
        for (let i = 0; i < N; i++) {
          const a = Math.random() * Math.PI * 2,
            s = rand(P * .3, P);
          add(Math.cos(a) * s, Math.sin(a) * s, {});
        }
        break;
      case 'chrysanthemum':
        for (let i = 0; i < N; i++) {
          const a = Math.random() * Math.PI * 2,
            s = rand(P * .4, P);
          add(Math.cos(a) * s, Math.sin(a) * s, {
            trail: true,
            life: rand(90, 140)
          });
        }
        break;
      case 'willow':
        for (let i = 0; i < N * .8; i++) {
          const a = Math.random() * Math.PI * 2,
            s = rand(P * .3, P * .75);
          add(Math.cos(a) * s, Math.sin(a) * s - 1, {
            trail: true,
            gravMul: 1.6,
            friction: .975,
            life: rand(140, 220),
            size: rand(1, 1.8),
            dh: -15
          });
        }
        break;
      case 'ring': {
        const tilt = rand(.3, 1),
          hue2 = (hue + rand(90, 180)) % 360;
        for (let i = 0; i < N; i++) {
          const a = (i / N) * Math.PI * 2;
          add(Math.cos(a) * P * .85, Math.sin(a) * P * .85 * tilt, {
            dh: (hue2 - hue),
            friction: .97,
            life: rand(70, 100)
          });
        }
        for (let i = 0; i < N * .25; i++) {
          const a = Math.random() * Math.PI * 2,
            s = rand(0, P * .3);
          add(Math.cos(a) * s, Math.sin(a) * s, {});
        }
      }
      break;
      case 'heart':
        for (let i = 0; i < N; i++) {
          const t = (i / N) * Math.PI * 2;
          const hx = 16 * Math.pow(Math.sin(t), 3),
            hy = -(13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t)),
            k = P / 17;
          add(hx * k * rand(.9, 1.1), hy * k * rand(.9, 1.1), {
            friction: .965,
            life: rand(80, 120),
            dh: rand(-10, 10)
          });
        }
        break;
      case 'star': {
        const pts = 5,
          inner = .45;
        for (let i = 0; i < N; i++) {
          const t = (i / N) * Math.PI * 2;
          const R = P * (inner + (1 - inner) * Math.abs(Math.cos(pts * t / 2))) * rand(.85, 1.15);
          add(Math.cos(t) * R, Math.sin(t) * R, {
            friction: .965,
            life: rand(80, 120)
          });
        }
      }
      break;
      case 'double': {
        const hue2 = (hue + 140) % 360;
        for (let i = 0; i < N * .7; i++) {
          const a = Math.random() * Math.PI * 2,
            s = rand(P * .6, P);
          add(Math.cos(a) * s, Math.sin(a) * s, {
            trail: true
          });
        }
        setTimeout(() => {
          for (let i = 0; i < N * .5; i++) {
            const a = Math.random() * Math.PI * 2,
              s = rand(P * .15, P * .45);
            particles.push(new Particle(cx, cy, Math.cos(a) * s, Math.sin(a) * s, hue2, {
              life: rand(50, 90)
            }));
          }
          boom(.6);
        }, 140);
      }
      break;
      case 'palm':
        for (let j = 0; j < 8; j++) {
          const baseA = (j / 8) * Math.PI * 2 + rand(-.1, .1);
          for (let i = 0; i < N / 8; i++) {
            const s = rand(P * .4, P);
            add(Math.cos(baseA) * s, Math.sin(baseA) * s - 1.2, {
              trail: true,
              gravMul: 1.4,
              friction: .978,
              life: rand(120, 180)
            });
          }
        }
        break;
      case 'crackle':
        for (let i = 0; i < N; i++) {
          const a = Math.random() * Math.PI * 2,
            s = rand(P * .3, P);
          add(Math.cos(a) * s, Math.sin(a) * s, {
            crackle: true,
            sparkle: true,
            life: rand(90, 150),
            size: rand(1, 2),
            dh: rand(-15, 15)
          });
        }
        crackleSound();
        break;
      case 'fisheye':
        for (let i = 0; i < N; i++) {
          const a = Math.random() * Math.PI * 2,
            s = P * rand(.85, 1.05);
          add(Math.cos(a) * s, Math.sin(a) * s, {
            friction: .995,
            life: rand(100, 150),
            trail: true,
            size: rand(1.5, 2.6)
          });
        }
        break;
      case 'v': {
        const dir = Math.random() < .5 ? 1 : -1;
        for (let i = 0; i < N; i++) {
          const a = dir * rand(.35, .9) + (dir > 0 ? -Math.PI / 2 : Math.PI / 2),
            s = rand(P * .4, P);
          add(Math.cos(a) * s, Math.sin(a) * s, {
            dh: rand(-25, 25)
          });
        }
      }
      break;
      default:
        for (let i = 0; i < N; i++) {
          const a = Math.random() * Math.PI * 2,
            s = rand(P * .3, P);
          add(Math.cos(a) * s, Math.sin(a) * s, {});
        }
      }
    }

    function explode(x, y, hue, shell, scale) {
      makeShell(shell, x, y, hue, scale);
      flashAlpha = Math.min(.35, flashAlpha + .12 * (scale || 1));
      boom(scale || 1);
      for (let i = 0; i < 12; i++) {
        const a = Math.random() * Math.PI * 2;
        sparks.push(new Particle(x, y, Math.cos(a) * rand(2, 5), Math.sin(a) * rand(2, 5), (hue + 40) % 360, {
          life: rand(10, 22),
          size: rand(1, 2),
          friction: .9,
          gravMul: 0
        }));
      }
    }
    /* -------- CONTROLS -------- */
    function bindRange(id, key, fmt) {
      const el = document.getElementById(id),
        out = document.getElementById(id + 'Out');
      const upd = () => {
        S[key] = parseFloat(el.value);
        out.textContent = fmt ? fmt(S[key]) : el.value;
      };
      el.addEventListener('input', upd);
      upd();
    }
    bindRange('gravity', 'gravity');
    bindRange('wind', 'wind', v => v.toFixed(2));
    bindRange('power', 'power');
    bindRange('count', 'count');
    bindRange('fade', 'fade');
    bindRange('autoRate', 'autoRate', v => v === 0 ? 'off' : v + '/s');
    document.getElementById('theme').addEventListener('change', e => setTheme(e.target.value, true));
    document.getElementById('shell').addEventListener('change', e => S.shell = e.target.value);
    document.getElementById('autoCycle').addEventListener('change', e => S.autoCycle = e.target.checked);
    document.getElementById('showStars').addEventListener('change', e => S.showStars = e.target.checked);
    document.getElementById('glow').addEventListener('change', e => S.glow = e.target.checked);
    document.getElementById('sound').addEventListener('change', e => {
      S.sound = e.target.checked;
      if (S.sound) audioCtx()?.resume?.();
    });
    document.getElementById('finaleBtn').addEventListener('click', () => grandFinale());
    document.getElementById('clearBtn').addEventListener('click', () => {
      rockets.length = 0;
      particles.length = 0;
      sparks.length = 0;
    });
    const panel = document.getElementById('panel'),
      panelToggle = document.getElementById('panelToggle');

    function togglePanel() {
      panel.classList.toggle('hidden');
      panelToggle.classList.toggle('show', panel.classList.contains('hidden'));
    }
    panelToggle.addEventListener('click', togglePanel);
    const tnEl = document.getElementById('themeName');

    function setTheme(key, announce) {
      themeKey = key;
      document.getElementById('theme').value = key;
      if (announce) {
        tnEl.textContent = '✦ ' + theme().name + ' ✦';
        tnEl.style.color = hsla(randHue(), 90, 75, 1);
        tnEl.classList.remove('pop');
        void tnEl.offsetWidth;
        tnEl.classList.add('pop');
      }
    }
    const themeKeys = Object.keys(THEMES);

    function nextTheme() {
      setTheme(themeKeys[(themeKeys.indexOf(themeKey) + 1) % themeKeys.length], true);
    }
    /* -------- INTERACTION -------- */
    const launchTo = (x, y, shell) => rockets.push(new Rocket(x, y, shell));
    canvas.addEventListener('pointerdown', e => launchTo(e.clientX, e.clientY));
    canvas.addEventListener('pointermove', e => {
      if (e.buttons & 1 && Math.random() < .25) launchTo(e.clientX, e.clientY);
    });
    canvas.addEventListener('dblclick', e => {
      const x = e.clientX,
        y = e.clientY;
      explode(x, y, randHue(), 'chrysanthemum', 1.8);
      setTimeout(() => explode(x + rand(-60, 60), y + rand(-60, 60), randHue(), 'willow', 1.4), 120);
      setTimeout(() => explode(x + rand(-60, 60), y + rand(-60, 60), randHue(), 'peony', 1.4), 240);
    });
    window.addEventListener('keydown', e => {
      if (e.target.tagName === 'SELECT' || e.target.tagName === 'INPUT') return;
      switch (e.key.toLowerCase()) {
      case ' ':
        e.preventDefault();
        rockets.push(new Rocket(rand(W * .15, W * .85), rand(H * .1, H * .45)));
        break;
      case 'f':
        grandFinale();
        break;
      case 't':
        nextTheme();
        break;
      case 'h':
        togglePanel();
        break;
      case 'c':
        rockets.length = 0;
        particles.length = 0;
        sparks.length = 0;
        break;
      case 's': {
        const cb = document.getElementById('sound');
        cb.checked = !cb.checked;
        S.sound = cb.checked;
        if (S.sound) audioCtx()?.resume?.();
        break;
      }
      }
    });
    /* -------- AUTO LAUNCH / CYCLE -------- */
    let autoAcc = 0,
      cycleAcc = 0;

    function autoLaunch(dt) {
      if (S.autoRate > 0) {
        autoAcc += dt * S.autoRate / 1000;
        while (autoAcc >= 1) {
          autoAcc--;
          rockets.push(new Rocket(rand(W * .1, W * .9), rand(H * .08, H * .5)));
        }
      }
      if (S.autoCycle) {
        cycleAcc += dt;
        if (cycleAcc > 20000) {
          cycleAcc = 0;
          nextTheme();
        }
      }
    }
    /* -------- GRAND FINALE -------- */
    let finaleActive = false;

    function grandFinale() {
      if (finaleActive) return;
      finaleActive = true;
      const shells = ['peony', 'chrysanthemum', 'willow', 'ring', 'heart', 'star', 'double', 'palm', 'crackle', 'fisheye', 'v'];
      let n = 0;
      const iv = setInterval(() => {
        n++;
        for (let k = 0; k < 3; k++) rockets.push(new Rocket(rand(W * .05, W * .95), rand(H * .06, H * .45), shells[(Math.random() * shells.length) | 0]));
        if (n === 14)
          for (let k = 0; k < 10; k++)
            setTimeout(() => explode(rand(W * .05, W * .95), rand(H * .1, H * .5), randHue(), shells[(Math.random() * shells.length) | 0], 1.5), k * 70);
        if (n > 20) {
          clearInterval(iv);
          finaleActive = false;
        }
      }, 130);
    }
    /* -------- MAIN LOOP -------- */
    let last = performance.now(),
      fpsAcc = 0,
      fpsN = 0;
    const fpsEl = document.getElementById('fps'),
      pcEl = document.getElementById('pcount');

    function hexWithAlpha(hex, a) {
      const r = parseInt(hex.slice(1, 3), 16),
        g = parseInt(hex.slice(3, 5), 16),
        b = parseInt(hex.slice(5, 7), 16);
      return `rgba(${r},${g},${b},${a})`;
    }

    function frame(now) {
      const dt = Math.min(50, now - last);
      last = now;
      ctx.globalCompositeOperation = 'source-over';
      ctx.fillStyle = hexWithAlpha(theme().bg, S.fade + 0.02);
      ctx.fillRect(0, 0, W, H);
      if (S.showStars) {
        ctx.save();
        for (const st of stars) {
          st.tw += dt * .001 * st.sp;
          const a = .25 + .55 * Math.abs(Math.sin(st.tw));
          ctx.fillStyle = `rgba(220,230,255,${a*.7})`;
          ctx.fillRect(st.x, st.y, st.r, st.r);
        }
        ctx.restore();
      }
      ctx.globalCompositeOperation = S.glow ? 'lighter' : 'source-over';
      for (let i = rockets.length - 1; i >= 0; i--) {
        const r = rockets[i];
        r.update();
        r.draw();
        if (r.dead) rockets.splice(i, 1);
      }
      for (let i = particles.length - 1; i >= 0; i--) {
        const p = particles[i];
        p.update();
        p.draw();
        if (p.dead) particles.splice(i, 1);
      }
      for (let i = sparks.length - 1; i >= 0; i--) {
        const p = sparks[i];
        p.update();
        p.draw();
        if (p.dead) sparks.splice(i, 1);
      }
      ctx.globalCompositeOperation = 'lighter';
      if (flashAlpha > .005) {
        ctx.fillStyle = `rgba(255,240,220,${flashAlpha*.12})`;
        ctx.fillRect(0, 0, W, H);
        flashAlpha *= .88;
      } else flashAlpha = 0;
      ctx.globalCompositeOperation = 'source-over';
      autoLaunch(dt);
      fpsAcc += dt;
      fpsN++;
      if (fpsAcc > 500) {
        fpsEl.textContent = Math.round(1000 / (fpsAcc / fpsN));
        fpsAcc = 0;
        fpsN = 0;
        pcEl.textContent = particles.length + sparks.length + rockets.length;
      }
      requestAnimationFrame(frame);
    }
    /* -------- BOOT -------- */
    resize();
    setTheme('classic', false);
    requestAnimationFrame(frame);
    setTimeout(() => grandFinale(), 400); // welcome salvo
  </script>
</body>

</html>
        
编辑器加载中
预览
控制台