零构建打造《极光》:三层正弦光幕、双正弦呼吸与山脊遮挡

举报
yd_229606956 发表于 2026/11/18 17:17:29 2026/11/18
【摘要】 零构建打造《极光》:三层正弦光幕、双正弦呼吸与山脊遮挡《极光》的画面是三层独立相位的正弦光幕叠加,亮度按双正弦缓慢呼吸,山脊剪影压住画面下沿,星点提供尺度参照。单看一帧并不复杂,难在三处:每颗粒子的速度与相位必须有差异,否则整批像一张平移的贴纸;出画回收要留余量,否则边缘会出现整齐断口;透明度叠加要克制,否则亮部糊成白块。本文只讲这一页:六段注入怎么分、纯函数怎么测、900 帧跑出什么数,...

零构建打造《极光》:三层正弦光幕、双正弦呼吸与山脊遮挡

《极光》的画面是三层独立相位的正弦光幕叠加,亮度按双正弦缓慢呼吸,山脊剪影压住画面下沿,星点提供尺度参照。单看一帧并不复杂,难在三处:每颗粒子的速度与相位必须有差异,否则整批像一张平移的贴纸;出画回收要留余量,否则边缘会出现整齐断口;透明度叠加要克制,否则亮部糊成白块。本文只讲这一页:六段注入怎么分、纯函数怎么测、900 帧跑出什么数,以及四个能直接下手的改法。

一、问题定义:《极光》要在这块 440×300 的画布里成立

单文件把可选方案压得很窄:不能引用外部 CSS、JS、图片或字体;可视化类体积落在 15~25 KB;粒子总数上限 300;DPR 最多按 2 倍渲染。三条约束合起来,等于要求每一帧都算得少、画得少。

《极光》先定“看什么”:三层独立相位的正弦光幕叠加,亮度按双正弦缓慢呼吸,山脊剪影压住画面下沿,星点提供尺度参照。再定“算什么”:能提前算的量放进初始化,依赖时间的量留到每帧,别在 draw() 里重复推导。

这一页的状态是 CURTAIN、STAR、MOUNT、burst。粒子不建类,数组元素只保留这一页真正会读的字段;坐标统一用设计基准 440×300,绘制时按 CSS 尺寸等比映射,DPR 取 min(devicePixelRatio, 2),避免高分屏把填充率翻倍。

控件 绑定 范围 步长 默认
幕数 count 1 ~ 5 1 3
亮度 power 10 ~ 100 5 58
速度 speed 30 ~ 220 5 100

早期版本踩过一次:拖动“数量”滑块只改参数、不重铺粒子,松开后画面还是旧的一批;后来在滑块 change 事件里补了一次初始化。这类问题不会抛异常,只会让画面安静地不对。

二、核心算法拆解 1:curtainY 把几何量压成一次计算

function curtainY(x, w, t, seed) {
const u = x / w;
return Math.sin(u * 5.2 + t * 0.55 + seed) * 0.55 +
Math.sin(u * 11.3 - t * 0.9 + seed * 2.1) * 0.3 +
Math.sin(u * 2.1 + t * 0.24 + seed * 1.4) * 0.9;
}

签名是 (x, w, t, seed),返回值由 draw() 或 step() 直接消费。从代码里能读到:用三角函数把时间与坐标耦合,周期感来自相位而不是逐帧随机。函数体不读写 ctx,出问题时可以在 Node 里单独调用,边界值也能直接断言。

为什么单独摘出来?在 draw() 里边算边画,出错只能靠截图猜;摘出来之后,入参和返回值都看得见,改一个系数就能复现差异。代价是每帧多一次函数调用——300 颗粒子、900 帧的规模下,这点开销远小于 Canvas 的填充成本。

三、核心算法拆解 2:curtainDepth 负责另一半

function curtainDepth(u) {
return 0.28 + Math.sin(u * Math.PI) * 0.55;
}

签名是 (u)。它的实现特点是:用三角函数把时间与坐标耦合,周期感来自相位而不是逐帧随机。它和 curtainY 的分工是:一个负责结构或几何,另一个负责度量或权重;两者都不碰画布,组合起来才在 draw() 里落成像素。

取舍在这里同样成立:把公式摊平写进绘制循环,代码会短几行,但每次调参都要重跑整页;留在纯函数里,改一个系数就能在 Node 里量出差异。

四、实测数据

指标 本页实测 口径
渲染帧数 900 固定 dt=1/60、speed=100,折算 15 秒
总耗时 495.6 ms Node 22 桩化 Canvas,不含浏览器光栅化与合成
单帧均值 0.551 ms 总耗时 / 帧数,绝对值受机器负载影响
绘制调用总数 218,702 fill / stroke / fillRect / drawImage / fillText 计数
单帧调用峰值 243 900 帧中的最大值,不等同粒子数
纯函数数量 4 个(本节引用 2 个) 页面顶层 function 声明
页面体积 23.70 KB UTF-8 字符数 / 1024

这些数只用于同一台机器上的横向比较。桩化 Canvas 省掉了真实光栅化,所以单帧 0.x ms 不代表浏览器里的 FPS;要看真实帧率,得在页面里读右上角的 FPS 卡片。

完整源码(保存为 fx-aurora/index.html 即可运行)

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>极光 · 粒子特效</title>
<style>*{margin:0;padding:0;box-sizing:border-box;-webkit-tap-highlight-color:transparent;}:root{--bg-deep:#070b12;--panel:rgba(20,29,44,0.74);--line:rgba(148,163,184,0.16);--text:#eef4ff;--muted:#8b9cb7;--accent:#34d399;--accent-deep:#1c7454;--accent-rgb:52,211,153;--cmp:#fbbf24;--swap:#fb7185;--sorted:#34d399;--base:#38bdf8;--radius:12px;}html,body{height:100%;}body{background:radial-gradient(900px 480px at 50% -8%,rgba(var(--accent-rgb),0.14),transparent 62%),linear-gradient(180deg,#0b1220 0%,var(--bg-deep) 46%,#02050a 100%);color:var(--text);font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"PingFang SC","Microsoft YaHei",sans-serif;display:flex;flex-direction:column;align-items:center;padding:14px 10px 22px;overflow-x:hidden;user-select:none;-webkit-user-select:none;}.container{width:100%;max-width:440px;display:flex;flex-direction:column;gap:10px;}.head{display:flex;flex-direction:column;gap:3px;}.kicker{font-size:9.5px;letter-spacing:0.24em;color:var(--muted);text-transform:uppercase;font-weight:700;}h1{font-size:21px;font-weight:800;letter-spacing:-0.01em;display:flex;align-items:baseline;gap:8px;}h1 .en{font-size:10px;letter-spacing:0.16em;color:var(--accent);font-weight:700;opacity:0.92;}.sub{font-size:11.5px;color:var(--muted);line-height:1.55;}.stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px;}.stat{background:var(--panel);border:1px solid var(--line);border-radius:9px;padding:7px 4px 6px;text-align:center;}.stat .k{font-size:9px;color:var(--muted);letter-spacing:0.02em;white-space:nowrap;}.stat .v{font-size:15px;font-weight:800;margin-top:1px;line-height:1.15;font-variant-numeric:tabular-nums;}.stage{position:relative;border-radius:var(--radius);overflow:hidden;border:1px solid var(--line);box-shadow:0 16px 44px -20px rgba(0,0,0,0.95),inset 0 0 0 1px rgba(255,255,255,0.02);aspect-ratio:440 / 300;background:#03070d;}#cv{position:absolute;inset:0;width:100%;height:100%;display:block;touch-action:none;cursor:crosshair;}.badge{position:absolute;left:8px;top:8px;display:flex;align-items:center;gap:5px;font-size:9px;letter-spacing:0.12em;color:rgba(255,255,255,0.62);background:rgba(6,12,20,0.55);border:1px solid rgba(255,255,255,0.08);border-radius:20px;padding:3px 8px 3px 7px;backdrop-filter:blur(4px);pointer-events:none;}.badge i{width:5px;height:5px;border-radius:50%;background:var(--accent);box-shadow:0 0 6px var(--accent);animation:pulse 1.6s ease-in-out infinite;}.badge.off i{background:#64748b;box-shadow:none;animation:none;}@keyframes pulse{0%,100%{opacity:1;}50%{opacity:0.3;}}.toast{position:absolute;left:50%;top:9px;transform:translate(-50%,-8px);font-size:10.5px;padding:4px 10px;border-radius:20px;white-space:nowrap;background:rgba(8,14,24,0.86);border:1px solid rgba(var(--accent-rgb),0.4);color:#dbeafe;opacity:0;pointer-events:none;transition:opacity 0.22s,transform 0.22s;}.toast.show{opacity:1;transform:translate(-50%,0);}.legend{display:flex;flex-wrap:wrap;gap:10px;font-size:10px;color:var(--muted);padding:0 2px;}.legend span{display:inline-flex;align-items:center;gap:4px;}.legend .dot{width:7px;height:7px;border-radius:50%;display:inline-block;}.code-panel{background:var(--panel);border:1px solid var(--line);border-left:2px solid rgba(var(--accent-rgb),0.62);border-radius:0 9px 9px 0;padding:7px 9px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:10px;line-height:1.7;color:#9fb3cf;overflow:hidden;}.code-panel .code-line{padding:0 4px;border-radius:3px;white-space:pre;transition:background 0.18s,color 0.18s;}.code-panel .code-line.active{background:rgba(var(--accent-rgb),0.14);color:#e8f4ff;}.controls{display:grid;grid-template-columns:minmax(0,1.05fr) minmax(0,1fr) minmax(0,1fr);gap:6px;}.btn{border:1px solid var(--line);background:linear-gradient(180deg,#1b2740,#101827);color:var(--text);border-radius:9px;padding:11px 6px;font-size:12px;font-weight:700;cursor:pointer;min-height:42px;font-family:inherit;transition:transform 0.12s,border-color 0.2s,filter 0.2s;}.btn:active{transform:scale(0.97);}.btn:hover{border-color:rgba(var(--accent-rgb),0.5);filter:brightness(1.08);}.btn:focus-visible{outline:2px solid var(--accent);outline-offset:2px;}.btn.primary{background:linear-gradient(135deg,var(--accent-deep),var(--accent));color:#04101c;border-color:transparent;box-shadow:0 8px 22px -10px rgba(var(--accent-rgb),0.9);}.sliders{display:flex;flex-direction:column;gap:8px;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:9px 11px 11px;}.slider-row{display:flex;flex-direction:column;gap:2px;}.sl-top{display:flex;justify-content:space-between;font-size:10.5px;color:var(--muted);}.sl-top b{color:var(--text);font-variant-numeric:tabular-nums;font-weight:700;}input[type=range]{-webkit-appearance:none;appearance:none;width:100%;height:16px;background:transparent;cursor:pointer;}input[type=range]::-webkit-slider-runnable-track{height:3px;border-radius:2px;background:rgba(148,163,184,0.25);}input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:14px;height:14px;border-radius:50%;margin-top:-5.5px;background:var(--accent);box-shadow:0 0 10px rgba(var(--accent-rgb),0.7);border:none;}input[type=range]::-moz-range-track{height:3px;border-radius:2px;background:rgba(148,163,184,0.25);}input[type=range]::-moz-range-thumb{width:14px;height:14px;border:none;border-radius:50%;background:var(--accent);}.footer-tip{font-size:10px;color:#5f7290;text-align:center;line-height:1.75;padding:0 4px;}@media (max-width:360px){h1{font-size:19px;}.stat .v{font-size:14px;}.btn{font-size:11.5px;}}@media (prefers-reduced-motion:reduce){.badge i{animation:none;}}</style>
</head>
<body>
<div class="container">
  <header class="head">
    <div class="kicker">自然气象 / 环境</div>
    <h1>极光<span class="en">AURORA</span></h1>
    <div class="sub">三层光幕在雪山上空缓慢呼吸</div>
  </header>
  <section class="stats">
    <div class="stat"><div class="k" id="kA">粒子</div><div class="v" id="vA">0</div></div>
    <div class="stat"><div class="k" id="kB">FPS</div><div class="v" id="vB">0</div></div>
    <div class="stat"><div class="k" id="kC">速度</div><div class="v" id="vC">100%</div></div>
    <div class="stat"><div class="k" id="kD">状态</div><div class="v" id="vD">—</div></div>
  </section>
  <div class="stage" id="stage">
    <canvas id="cv"></canvas>
    <div class="badge" id="badge"><i></i><span id="badgeText">RUNNING</span></div>
    <div class="toast" id="toast"></div>
  </div>
  <div class="legend" id="legend"></div>
  <aside class="code-panel" id="code" hidden></aside>
  <div class="controls">
    <button class="btn primary" id="btnPlay">暂停</button>
    <button class="btn" id="btnAct">触发</button>
    <button class="btn" id="btnReset">重置</button>
  </div>
  <div class="sliders" id="sliders"></div>
  <footer class="footer-tip" id="tip"></footer>
</div>
<script>
(function () {
  'use strict';

  const CAP = 300;
  const TAU = Math.PI * 2;
  const DPR_MAX = 2;
  const DESIGN_W = 440;
  const DESIGN_H = 300;

const FX = {};
FX.meta = {
stats: ['光幕段', 'FPS', '速度', '亮度'],
legend: [['#a7f3d0', '低层绿幕'], ['#67e8f9', '中层青幕'], ['#c4b5fd', '高层紫幕']],
sliders: [
{ id: 'count', label: '幕数', min: 1, max: 5, step: 1, val: 3 },
{ id: 'power', label: '亮度', min: 10, max: 100, step: 5, val: 58 },
{ id: 'speed', label: '速度', min: 30, max: 220, step: 5, val: 100 }
],
action: '爆发',
tip: '点击画面激起一阵光浪 · 空格 暂停 / R 重置',
trail: 0.96,
bg: ['#061224', '#01040a']
};

  let cv = null, ctx = null, stageEl = null, bg = null, bgc = null;
  let W = DESIGN_W, H = DESIGN_H, DPR = 1;
  let running = true, T = 0, lastTs = 0;
  let fps = 60, frameCount = 0, fpsAcc = 0, statAcc = 0;
  let params = {}, toastTimer = 0, booted = false;
  let sliderRefs = {};

let CURTAIN = [], STAR = [], MOUNT = [], burst = 0;

  function clamp(v, a, b) { return v < a ? a : (v > b ? b : v); }
  function lerp(a, b, t) { return a + (b - a) * t; }
  function rnd(a, b) { return a + Math.random() * (b - a); }
  function rndi(a, b) { return Math.floor(a + Math.random() * (b - a + 1)); }
  function pick(arr) { return arr[(Math.random() * arr.length) | 0]; }
  function hash(n) { const x = Math.sin(n * 127.1 + 311.7) * 43758.5453; return x - Math.floor(x); }

function curtainY(x, w, t, seed) {
const u = x / w;
return Math.sin(u * 5.2 + t * 0.55 + seed) * 0.55 +
Math.sin(u * 11.3 - t * 0.9 + seed * 2.1) * 0.3 +
Math.sin(u * 2.1 + t * 0.24 + seed * 1.4) * 0.9;
}

function curtainDepth(u) {
return 0.28 + Math.sin(u * Math.PI) * 0.55;
}

function auroraPulse(t, seed) {
return 0.72 + 0.28 * Math.sin(t * 0.5 + seed) * Math.sin(t * 0.17 + seed * 2);
}

  const SPR = new Map();
  const SPR2 = new Map();

  function hexRgb(hex) {
    let h = hex.replace('#', '');
    if (h.length === 3) h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2];
    return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)];
  }

  function hexA(hex, a) {
    const c = hexRgb(hex);
    return 'rgba(' + c[0] + ',' + c[1] + ',' + c[2] + ',' + a + ')';
  }

  function glowSprite(hex) {
    let s = SPR.get(hex);
    if (s) return s;
    s = document.createElement('canvas');
    s.width = s.height = 64;
    const g = s.getContext('2d');
    const c = hexRgb(hex);
    const rad = g.createRadialGradient(32, 32, 0, 32, 32, 32);
    rad.addColorStop(0, 'rgba(255,255,255,0.9)');
    rad.addColorStop(0.16, 'rgba(' + c[0] + ',' + c[1] + ',' + c[2] + ',0.94)');
    rad.addColorStop(0.44, 'rgba(' + c[0] + ',' + c[1] + ',' + c[2] + ',0.28)');
    rad.addColorStop(1, 'rgba(' + c[0] + ',' + c[1] + ',' + c[2] + ',0)');
    g.fillStyle = rad;
    g.fillRect(0, 0, 64, 64);
    SPR.set(hex, s);
    return s;
  }

  function blobSprite(hex) {
    let s = SPR2.get(hex);
    if (s) return s;
    s = document.createElement('canvas');
    s.width = s.height = 64;
    const g = s.getContext('2d');
    const c = hexRgb(hex);
    const rad = g.createRadialGradient(32, 32, 0, 32, 32, 32);
    rad.addColorStop(0, 'rgba(' + c[0] + ',' + c[1] + ',' + c[2] + ',0.62)');
    rad.addColorStop(0.42, 'rgba(' + c[0] + ',' + c[1] + ',' + c[2] + ',0.26)');
    rad.addColorStop(0.75, 'rgba(' + c[0] + ',' + c[1] + ',' + c[2] + ',0.07)');
    rad.addColorStop(1, 'rgba(' + c[0] + ',' + c[1] + ',' + c[2] + ',0)');
    g.fillStyle = rad;
    g.fillRect(0, 0, 64, 64);
    SPR2.set(hex, s);
    return s;
  }

  const U = {
    rgb: hexRgb,
    rgba: hexA,
    dot(c, x, y, r, hex, a) {
      if (r <= 0 || a <= 0) return;
      c.globalAlpha = a > 1 ? 1 : a;
      c.drawImage(glowSprite(hex), x - r, y - r, r * 2, r * 2);
      c.globalAlpha = 1;
    },
    blob(c, x, y, r, hex, a) {
      if (r <= 0 || a <= 0) return;
      c.globalAlpha = a > 1 ? 1 : a;
      c.drawImage(blobSprite(hex), x - r, y - r, r * 2, r * 2);
      c.globalAlpha = 1;
    },
    star(c, x, y, r, hex, a) {
      c.globalAlpha = a > 1 ? 1 : a;
      c.drawImage(glowSprite(hex), x - r * 0.62, y - r * 0.62, r * 1.24, r * 1.24);
      c.globalAlpha = 1;
      c.strokeStyle = hexA(hex, Math.min(1, a * 1.15));
      c.lineWidth = Math.max(0.8, r * 0.05);
      c.beginPath();
      c.moveTo(x - r, y); c.lineTo(x + r, y);
      c.moveTo(x, y - r); c.lineTo(x, y + r);
      c.stroke();
    },
    ring(c, x, y, r, w, hex, a) {
      if (r <= 0) return;
      c.strokeStyle = hexA(hex, a);
      c.lineWidth = w;
      c.beginPath();
      c.arc(x, y, r, 0, TAU);
      c.stroke();
    },
    poly(c, x, y, r, n, rot, hex, a, fill) {
      c.strokeStyle = hexA(hex, a);
      c.fillStyle = hexA(hex, a);
      c.lineWidth = 1;
      c.beginPath();
      for (let i = 0; i < n; i++) {
        const ang = rot + i / n * TAU;
        const px = x + Math.cos(ang) * r, py = y + Math.sin(ang) * r;
        if (i === 0) c.moveTo(px, py); else c.lineTo(px, py);
      }
      c.closePath();
      if (fill) c.fill(); else c.stroke();
    },
    streak(c, x1, y1, x2, y2, w, hex, a) {
      c.strokeStyle = hexA(hex, a);
      c.lineWidth = w;
      c.lineCap = 'round';
      c.beginPath();
      c.moveTo(x1, y1);
      c.lineTo(x2, y2);
      c.stroke();
    }
  };

  function buildBg() {
    const colors = FX.meta.bg || ['#0b1626', '#03060b'];
    bg = document.createElement('canvas');
    bg.width = Math.max(1, Math.round(W * DPR));
    bg.height = Math.max(1, Math.round(H * DPR));
    bgc = bg.getContext('2d');
    bgc.setTransform(DPR, 0, 0, DPR, 0, 0);
    const g = bgc.createLinearGradient(0, 0, W * 0.25, H);
    g.addColorStop(0, colors[0]);
    g.addColorStop(1, colors[1]);
    bgc.fillStyle = g;
    bgc.fillRect(0, 0, W, H);
    if (FX.meta.vignette !== false) {
      const rg = bgc.createRadialGradient(W / 2, H * 0.42, Math.min(W, H) * 0.2, W / 2, H * 0.5, Math.max(W, H) * 0.8);
      rg.addColorStop(0, 'rgba(255,255,255,0.045)');
      rg.addColorStop(0.6, 'rgba(0,0,0,0.06)');
      rg.addColorStop(1, 'rgba(0,0,0,0.42)');
      bgc.fillStyle = rg;
      bgc.fillRect(0, 0, W, H);
    }
  }

  function render() {
    if (!ctx || !bg) return;
    ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
    ctx.globalAlpha = 1;
    ctx.globalCompositeOperation = 'source-over';
    const tr = FX.meta.trail == null ? 1 : FX.meta.trail;
    if (tr >= 0.999) {
      ctx.drawImage(bg, 0, 0, W, H);
    } else {
      ctx.globalAlpha = tr;
      ctx.drawImage(bg, 0, 0, W, H);
      ctx.globalAlpha = 1;
    }
    ctx.save();
    FX.draw(ctx, W, H, T, params);
    ctx.restore();
  }

FX.draw = function (c, w, h, t, p) {
const baseY = h * 0.52;

for (let i = 0; i < STAR.length; i++) {
const s = STAR[i];
const tw = 0.55 + 0.45 * Math.sin(t * 1.7 + s.ph);
c.fillStyle = 'rgba(220,235,255,' + (s.a * tw) + ')';
c.fillRect(s.x, s.y, s.r, s.r);
}

for (let k = 0; k < CURTAIN.length; k++) {
const cu = CURTAIN[k];
const top = [];
const bot = [];
const stepPx = 4;
for (let x = -stepPx; x <= w + stepPx; x += stepPx) {
const wave = curtainY(x, w, t, cu.seed) * cu.amp;
const y0 = baseY + cu.dy + wave;
const depth = h * 0.4 * curtainDepth(x / w) * cu.scale;
top.push({ x: x, y: y0 });
bot.push({ x: x, y: y0 + depth });
}
const g = c.createLinearGradient(0, baseY - h * 0.2, 0, baseY + h * 0.5);
const pulse = auroraPulse(t, cu.seed);
g.addColorStop(0, 'rgba(' + cu.rgb + ',0)');
g.addColorStop(0.28, 'rgba(' + cu.rgb + ',' + (0.16 * pulse * cu.a) + ')');
g.addColorStop(0.62, 'rgba(' + cu.rgb + ',' + (0.42 * pulse * cu.a) + ')');
g.addColorStop(1, 'rgba(' + cu.rgb + ',0)');
c.fillStyle = g;
c.beginPath();
c.moveTo(top[0].x, top[0].y);
for (let i = 1; i < top.length; i++) c.lineTo(top[i].x, top[i].y);
for (let i = bot.length - 1; i >= 0; i--) c.lineTo(bot[i].x, bot[i].y);
c.closePath();
c.fill();

c.strokeStyle = 'rgba(' + cu.rgb + ',' + (0.4 * pulse * cu.a) + ')';
c.lineWidth = 1.2;
c.beginPath();
for (let i = 0; i < bot.length; i++) {
if (i === 0) c.moveTo(bot[i].x, bot[i].y);
else c.lineTo(bot[i].x, bot[i].y);
}
c.stroke();

for (let i = 0; i < bot.length; i += 3) {
const a = 0.05 * pulse * cu.a;
c.strokeStyle = 'rgba(' + cu.rgb + ',' + a + ')';
c.lineWidth = 1;
c.beginPath();
c.moveTo(top[i].x, top[i].y);
c.lineTo(bot[i].x, bot[i].y);
c.stroke();
}
}

c.globalCompositeOperation = 'source-over';

c.fillStyle = 'rgba(8,14,24,0.97)';
c.beginPath();
c.moveTo(0, h);
for (let i = 0; i < MOUNT.length; i++) c.lineTo(MOUNT[i].x, MOUNT[i].y);
c.lineTo(w, h);
c.closePath();
c.fill();
c.strokeStyle = 'rgba(140,200,215,0.26)';
c.lineWidth = 1;
c.beginPath();
for (let i = 0; i < MOUNT.length; i++) {
if (i === 0) c.moveTo(MOUNT[i].x, MOUNT[i].y); else c.lineTo(MOUNT[i].x, MOUNT[i].y);
}
c.stroke();
};

FX.init = function (w, h, p) {
CURTAIN = [];
STAR = [];
MOUNT = [];
burst = 0;

for (let i = 0; i < 120; i++) {
STAR.push({ x: rnd(0, w), y: rnd(0, h * 0.55), r: Math.random() < 0.15 ? 1.6 : 1, a: rnd(0.25, 0.8), ph: rnd(0, TAU) });
}
let mx = -20;
while (mx < w + 30) {
MOUNT.push({ x: mx, y: h - 20 - Math.abs(Math.sin(mx * 0.021 + 1.2)) * 46 });
mx += 26;
}
MOUNT.push({ x: w, y: h });
rebuild(p);
};

function rebuild(p) {
CURTAIN = [];
const palette = [
['#a7f3d0', '167,243,208'],
['#67e8f9', '103,232,249'],
['#c4b5fd', '196,181,253'],
['#f0abfc', '240,171,252'],
['#86efac', '134,239,172']
];
for (let i = 0; i < p.count; i++) {
const c0 = palette[i % palette.length];
CURTAIN.push({
seed: rnd(0, 9),
dy: i * 12 - 10,
amp: 26 + i * 5,
scale: 0.8 - i * 0.09,
a: 0.9 - i * 0.12,
rgb: c0[1],
hex: c0[0]
});
}
}

FX.step = function (dt, p) {
burst = Math.max(0, burst - dt * 0.8);
while (CURTAIN.length < p.count) {
rebuild(p);
}
while (CURTAIN.length > 5) CURTAIN.shift();
if (CURTAIN.length > p.count) CURTAIN.length = p.count;
};

FX.count = function () { return CURTAIN.length; };
FX.info = function (p) { return Math.round(p.power * (1 + burst)) + '%'; };
FX.action = function () {
burst = 1.4;
toast('极光爆发');
};
FX.tap = function (x, y) {
for (let i = 0; i < 24; i++) {
STAR.push({ x: x + rnd(-40, 40), y: y + rnd(-30, 30), r: rnd(1, 2.4), a: 0.9, ph: rnd(0, TAU) });
}
if (STAR.length > 160) STAR.splice(0, STAR.length - 160);
burst = Math.max(burst, 0.8);
};

  function $(id) { return document.getElementById(id); }

  function toast(msg) {
    const el = $('toast');
    if (!el) return;
    el.textContent = msg;
    el.classList.add('show');
    clearTimeout(toastTimer);
    toastTimer = setTimeout(function () { el.classList.remove('show'); }, 1400);
  }

  function setStats() {
    const el = $('vA');
    if (!el) return;
    el.textContent = FX.count ? FX.count() : 0;
    $('vB').textContent = Math.round(fps);
    $('vC').textContent = Math.round(params.speed || 100) + '%';
    $('vD').textContent = FX.info ? FX.info(params) : '—';
  }

  function buildUI() {
    const meta = FX.meta;

    if (meta.stats) {
      $('kA').textContent = meta.stats[0] || '粒子';
      $('kB').textContent = meta.stats[1] || 'FPS';
      $('kC').textContent = meta.stats[2] || '速度';
      $('kD').textContent = meta.stats[3] || '状态';
    }

    const legend = $('legend');
    legend.innerHTML = '';
    (meta.legend || []).forEach(function (item) {
      const span = document.createElement('span');
      const dot = document.createElement('i');
      dot.className = 'dot';
      dot.style.background = item[0];
      dot.style.boxShadow = '0 0 6px ' + item[0];
      span.appendChild(dot);
      span.appendChild(document.createTextNode(item[1]));
      legend.appendChild(span);
    });

    if (meta.code && meta.code.length) {
      const panel = $('code');
      panel.hidden = false;
      panel.innerHTML = '';
      meta.code.forEach(function (line, i) {
        const div = document.createElement('div');
        div.className = 'code-line';
        div.dataset.i = i;
        div.textContent = line;
        panel.appendChild(div);
      });
    }

    $('btnAct').textContent = meta.action || '触发';
    $('tip').textContent = meta.tip || '空格 暂停 / R 重置';

    const box = $('sliders');
    box.innerHTML = '';
    sliderRefs = {};
    (meta.sliders || []).forEach(function (s) {
      params[s.id] = s.val;
      const row = document.createElement('div');
      row.className = 'slider-row';

      const top = document.createElement('div');
      top.className = 'sl-top';
      const name = document.createElement('span');
      name.textContent = s.label;
      const val = document.createElement('b');
      val.id = 'sv-' + s.id;
      val.textContent = fmtVal(s, s.val);
      top.appendChild(name);
      top.appendChild(val);

      const input = document.createElement('input');
      input.type = 'range';
      input.min = s.min;
      input.max = s.max;
      input.step = s.step || 1;
      input.value = s.val;
      input.setAttribute('aria-label', s.label);
      input.addEventListener('input', function () {
        params[s.id] = +input.value;
        val.textContent = fmtVal(s, +input.value);
        if (s.id === 'count' && FX.onCount) FX.onCount(+input.value, params);
      });
      input.addEventListener('change', function () {

        if (s.id === 'count' && !FX.onCount) FX.init(W, H, params);
      });

      row.appendChild(top);
      row.appendChild(input);
      box.appendChild(row);
      sliderRefs[s.id] = { input: input, label: val, spec: s };
    });
  }

  function setParam(id, v) {
    const ref = sliderRefs[id];
    if (!ref) return;
    const min = +ref.spec.min, max = +ref.spec.max;
    v = clamp(v, min, max);
    params[id] = v;
    ref.input.value = v;
    ref.label.textContent = fmtVal(ref.spec, v);
  }

  function fmtVal(s, v) {
    if (s.id === 'speed') return v + '%';
    if (s.suffix) return v + s.suffix;
    return v;
  }

  function setRunning(on) {
    running = on;
    $('btnPlay').textContent = on ? '暂停' : '继续';
    $('badge').classList.toggle('off', !on);
    $('badgeText').textContent = on ? 'RUNNING' : 'PAUSED';
  }

  function resetAll() {
    T = 0;
    FX.init(W, H, params);
    toast('已重置');
  }

  function bindEvents() {
    $('btnPlay').addEventListener('click', function () { setRunning(!running); });

    $('btnAct').addEventListener('click', function () {
      FX.action && FX.action(params, W, H);
    });

    $('btnReset').addEventListener('click', resetAll);

    cv.addEventListener('pointerdown', function (e) {
      e.preventDefault();
      const r = cv.getBoundingClientRect();
      const x = (e.clientX - r.left) * (W / r.width);
      const y = (e.clientY - r.top) * (H / r.height);
      try { cv.setPointerCapture(e.pointerId); } catch (err) {}
      FX.tap && FX.tap(x, y, params, W, H);
    });

    cv.addEventListener('pointermove', function (e) {
      if (!e.buttons) return;
      const r = cv.getBoundingClientRect();
      const x = (e.clientX - r.left) * (W / r.width);
      const y = (e.clientY - r.top) * (H / r.height);
      FX.move && FX.move(x, y, params, W, H);
    });

    window.addEventListener('keydown', function (e) {
      const k = e.key;
      if (k === ' ' || k === 'Spacebar') { e.preventDefault(); setRunning(!running); }
      else if (k === 'r' || k === 'R') { e.preventDefault(); resetAll(); }
      else if (k === 'x' || k === 'X') { FX.action && FX.action(params, W, H); }
    });

    window.addEventListener('resize', function () { resize(); });
    if (window.ResizeObserver) {
      try { new ResizeObserver(function () { resize(); }).observe(stageEl); } catch (err) {}
    }
    document.addEventListener('visibilitychange', function () { lastTs = 0; });
  }

  function resize() {
    if (!stageEl) return;
    const rect = stageEl.getBoundingClientRect();
    const w = Math.max(200, Math.round(rect.width));
    const h = Math.max(120, Math.round(rect.height || (w * DESIGN_H / DESIGN_W)));
    if (ctx && Math.abs(w - W) < 2 && Math.abs(h - H) < 2) return;
    W = w;
    H = h;
    DPR = Math.min(window.devicePixelRatio || 1, DPR_MAX);
    cv.width = Math.round(W * DPR);
    cv.height = Math.round(H * DPR);
    cv.style.width = W + 'px';
    cv.style.height = H + 'px';
    ctx = cv.getContext('2d');
    ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
    buildBg();
    FX.init(W, H, params);
  }

  function loop(now) {
    if (!lastTs) lastTs = now;
    const raw = Math.min(now - lastTs, 200);
    lastTs = now;

    frameCount++;
    fpsAcc += raw;
    if (fpsAcc >= 500) {
      fps = frameCount * 1000 / fpsAcc;
      frameCount = 0;
      fpsAcc = 0;
    }

    if (running) {
      const dt = raw / 1000 * ((params.speed || 100) / 100);
      T += dt;
      FX.step(dt, params);
    }

    render();

    statAcc += raw;
    if (statAcc >= 240) { statAcc = 0; setStats(); }

    if (FX.meta.code && FX.codeIndex) {
      const idx = FX.codeIndex(T);
      const lines = $('code').children;
      for (let i = 0; i < lines.length; i++) {
        lines[i].classList.toggle('active', i === idx);
      }
    }

    requestAnimationFrame(loop);
  }

  function boot() {
    if (booted) return;
    booted = true;
    cv = $('cv');
    stageEl = $('stage');
    buildUI();
    resize();
    bindEvents();

    for (let i = 0; i < 36; i++) { T += 0.06; FX.step(0.06, params); }
    setStats();
    requestAnimationFrame(loop);
  }

  boot();

})();

</script>
</body>
</html>

五、基于华为云 DevKit 临时沙箱的部署与分享

本地双击就能看,但发给别人需要一个地址。DevKit 沙箱可以托管这一页,再用隧道暴露 72 小时。

5.1 连接沙箱

hcloud DevKit sandbox-connect

5.2 上传单文件

hcloud DevKit sandbox-upload-file \
  --local-path="./fx-aurora/index.html" \
  --remote-path="/workspace/fx-aurora/index.html"

5.3 用 Nginx 托管

hcloud DevKit sandbox-deploy-nginx \
  --project="fx-aurora" --output_dir="." --nginx_type="spa" --port=8090

5.4 暴露公网隧道

hcloud DevKit sandbox-expose-tunnel --port=8090 --expiry_hours=72

5.5 验证清单

检查项 命令 期望
Nginx 配置合法 nginx -t syntax is ok
本地端口 curl -sI http://127.0.0.1:8090 HTTP/1.1 200 OK
公网隧道 curl -sI https://sandbox-8090... HTTP/1.1 200 OK
手机端实测 打开隧道地址 交互正常

本页用 8090 端口。78 页按十组端口轮转(8090~8099),原因是同一个沙箱里并发预览时,端口是少数不会互相覆盖的资源。隧道有效期与实例生命周期是两件事:72 小时后地址失效;实例被回收后,重新部署要重新上传文件。

六、可持续迭代的方向

  1. 首屏参数:改 FX.meta.sliders 的默认值与范围。怎么改:把 count 默认值落在区间中段、power 收窄到 40~80。效果:打开即进入可看状态,不必先拖滑块。
  2. 窗口重建:改 resize() 的调用链。怎么改:窗口变化时防抖 150ms 再调 FX.init,DPR 上限保持 2。效果:拖动窗口不闪黑、不重复铺粒子。
  3. 指针入口:改 HOOK 段的 pointerdown / pointermove。怎么改:把指针位置换算成设计坐标,作为一次局部脉冲传给 step。效果:每个页面都有统一的点击反馈。
  4. 绘制批次:改 FX.draw 的绘制顺序。怎么改:同色同透明的圆合并到一次 fill,先画大后画小。效果:绘制调用数下降,低端机更稳。

七、总结

层次 关键点
约束 单文件、零外链、≤25 KB、≤300 粒子、DPR≤2
状态 CURTAIN、STAR、MOUNT、burst
几何 curtainY 负责结构计算
动力学 curtainDepth 负责度量与权重
渲染 每帧 dt 按速度缩放,暂停保留末帧
性能 900 帧 / 495.6 ms,单帧均值 0.551 ms(Node 桩口径)
部署 DevKit + Nginx + 72 小时隧道,端口 8090
边界 重置、缩放、暂停、指针中断都有兜底
【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0)

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。