全部动画

09

闪电

乌云、阶梯先导、回击闪光、余辉,每一次落雷形状都不同。

  • 电与光
  • 周期 1.3s
  • Canvas,内含一小段脚本
  • 无依赖

自定义

配色
预览背景

代码

<!--
  "Lightning" loader by onemilliontools.com
  https://loading.onemilliontools.com/loaders/lightning
  License: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/)
  Keep this notice, or credit "onemilliontools.com" with a link, wherever you use it.
-->
<div id="omt-loader"></div>
<script>
const OMT_SPEC = {
  w: 96, h: 96, label: "Lightning",
  create(g) {
    const { x, dot, TH, TAU, mix } = g, T = 1300;
    let main = null, brs = [], cyc = -1, ex = 48;
    const CL = [[22, 22, 9], [33, 16, 12], [48, 13, 14], [63, 17, 12], [72, 23, 7], [44, 24, 12], [58, 25, 10], [30, 26, 7]];
    const HL = [[33, 12, 8], [48, 9, 9], [62, 13, 7], [23, 18, 5]];

    // midpoint displacement: the offset is proportional to the segment length
    function bolt(x0, y0, x1, y1, rough, depth) {
      let pts = [[x0, y0], [x1, y1]];
      for (let d = 0; d < depth; d++) {
        const n = [];
        for (let i = 0; i < pts.length - 1; i++) {
          const a = pts[i], b = pts[i + 1], dx = b[0] - a[0], dy = b[1] - a[1], len = Math.hypot(dx, dy) || 1, off = (Math.random() - .5) * len * rough;
          n.push(a); n.push([(a[0] + b[0]) / 2 - dy / len * off, (a[1] + b[1]) / 2 + dx / len * off]);
        }
        n.push(pts[pts.length - 1]); pts = n;
      }
      return pts;
    }
    function stroke3(pts, al, w) {
      [[7, .22, TH.c1], [3, .5, TH.c1], [1.4, 1, TH.c2]].forEach(([lw, a, col]) => {
        x.globalAlpha = Math.min(1, a * al); x.strokeStyle = col; x.lineWidth = lw * w; x.lineCap = "round"; x.lineJoin = "round";
        x.beginPath(); pts.forEach((q, j) => j ? x.lineTo(q[0], q[1]) : x.moveTo(q[0], q[1])); x.stroke();
      });
    }
    function gen() {
      const sx = 36 + Math.random() * 24; ex = sx + (Math.random() - .5) * 26;
      main = bolt(sx, 28, ex, 89, .5, 6); brs = [];
      const n = main.length, ks = [.22, .4, .58, .74].map(f => Math.floor(f * n + Math.random() * 4));
      ks.forEach((k, i) => {
        const s = main[k], dir = (i % 2 ? 1 : -1) * (Math.random() > .2 ? 1 : -1), ang = Math.PI / 2 + dir * (.55 + Math.random() * .5), len = 16 + Math.random() * 16;
        const e = [s[0] + Math.cos(ang) * len, Math.min(88, s[1] + Math.sin(ang) * len)];
        const pts = bolt(s[0], s[1], e[0], e[1], .5, 4);
        brs.push({ root: k, pts, w: .55 });
        if (Math.random() < .7) {
          const j = Math.floor(pts.length * (.4 + Math.random() * .3)), q = pts[j], a2 = ang + dir * (.5 + Math.random() * .4), l2 = len * .5;
          brs.push({ root: k + j * .5, pts: bolt(q[0], q[1], q[0] + Math.cos(a2) * l2, Math.min(88, q[1] + Math.sin(a2) * l2), .5, 3), w: .35 });
        }
      });
    }
    return function (t) {
      const c = Math.floor(t / T), p = (t % T) / T;
      if (c !== cyc) { cyc = c; gen(); }
      // stepped leader (0 to 16 %) -> return stroke flash -> second flicker -> afterglow
      const LD = .16, f = Math.min(1, p / LD);
      let b = 0;
      if (p >= LD) { const q = p - LD; b = Math.exp(-q * 5.5) * (.75 + .25 * Math.cos(q * 40)) + .6 * Math.exp(-Math.pow((q - .2) * 16, 2)); }
      const cf = p < LD ? .12 * f : Math.min(1, b);
      x.clearRect(0, 0, 96, 96);
      dot(x, 48, 22, 36, TH.c2, .28 * cf);
      const base = mix(TH.c1, TH.c2, .5 * cf), hl = mix(mix(TH.c1, "#ffffff", .28), TH.c2, .75 * cf);
      x.globalAlpha = 1; x.fillStyle = base; x.beginPath(); CL.forEach(([cx, cy, r]) => { x.moveTo(cx + r, cy); x.arc(cx, cy, r, 0, TAU); }); x.fill();
      x.fillStyle = hl; x.globalAlpha = .85; x.beginPath(); HL.forEach(([cx, cy, r]) => { x.moveTo(cx + r, cy); x.arc(cx, cy, r, 0, TAU); }); x.fill();
      const nM = main.length, rev = p < LD ? f * (nM - 1) : nM - 1, al = p < LD ? .7 : b, w = p < LD ? .5 : .8;
      if (al > .02) {
        stroke3(main.slice(0, Math.floor(rev) + 1), al, w);
        brs.forEach(br => {
          let m = br.pts.length;
          if (p < LD) m = Math.floor((rev - br.root) * 1.3);
          if (m >= 2) stroke3(br.pts.slice(0, Math.min(br.pts.length, m)), al * .9, br.w * (p < LD ? .7 : 1));
        });
      }
      if (p >= LD && b > .03) { dot(x, ex, 88, 12 * b, TH.c2, .35 * b); dot(x, ex, 88, 5 * b, TH.c2, .7 * b); }
      x.globalAlpha = 1;
    };
  }
};

/* ---- omt runtime (shared by every canvas loader, no need to edit) ---- */
function omtLoader(root, spec, opts) {
  var o = { c1: "#2979FF", c2: "#FF9100", speed: 1, size: 96 };
  if (opts) for (var k in opts) if (opts[k] != null) o[k] = opts[k];
  var TAU = Math.PI * 2;
  var TH = { c1: o.c1, c2: o.c2, v: 0 };
  var cache = {};
  function hx(c) { return [1, 3, 5].map(function (i) { return parseInt(c.slice(i, i + 2), 16); }); }
  function rgb(a, b, k) { return "rgb(" + a.map(function (v, j) { return Math.round(v + (b[j] - v) * k); }).join() + ")"; }
  function mix(c1, c2, k) { return rgb(hx(c1), hx(c2), k); }
  function pal(c1, c2, n) { var a = hx(c1), b = hx(c2), r = []; for (var i = 0; i < n; i++) r.push(rgb(a, b, n > 1 ? i / (n - 1) : 0)); return r; }
  function P(n) { var key = n + ":" + TH.v; return cache[key] || (cache[key] = pal(TH.c1, TH.c2, n)); }
  function fr(v) { return Math.abs(Math.sin(v * 12.9898) * 43758.5453) % 1; }
  function dot(x, px, py, r, col, al) { x.globalAlpha = al; x.fillStyle = col; x.beginPath(); x.arc(px, py, r, 0, TAU); x.fill(); }

  var cv = document.createElement("canvas");
  cv.setAttribute("role", "img");
  cv.setAttribute("aria-label", spec.label || "Loading");
  cv.style.display = "block";
  var x = cv.getContext("2d");
  var dpr = Math.min(3, Math.max(1, window.devicePixelRatio || 1));
  function applySize() {
    var k = o.size / 96, s = dpr * k;
    cv.width = Math.round(spec.w * s);
    cv.height = Math.round(spec.h * s);
    cv.style.width = spec.w * k + "px";
    cv.style.height = spec.h * k + "px";
    x.setTransform(s, 0, 0, s, 0, 0);
  }

  var draw = spec.create({ x: x, W: spec.w, H: spec.h, TAU: TAU, TH: TH, P: P, pal: pal, mix: mix, hx: hx, fr: fr, dot: dot });
  var VT = 0, last = 0, raf = 0, running = false, visible = true;
  var mq = window.matchMedia ? window.matchMedia("(prefers-reduced-motion: reduce)") : { matches: false };

  function frame(t) {
    raf = 0;
    if (!running) return;
    var d = t - last, dt = 0;
    last = t;
    if (d > 0 && d < 200) { dt = d * o.speed; VT += dt; }
    draw(VT, dt);
    raf = requestAnimationFrame(frame);
  }
  function start() { if (running) return; running = true; last = 0; raf = requestAnimationFrame(frame); }
  function stop() { running = false; if (raf) cancelAnimationFrame(raf); raf = 0; }
  function still() { for (var i = 0; i < 120; i++) { VT += 16.7; draw(VT, 16.7); } }
  function sync() {
    if (mq.matches) { stop(); still(); }
    else if (visible && !document.hidden) start();
    else stop();
  }
  var io = window.IntersectionObserver ? new IntersectionObserver(function (e) { visible = e[0].isIntersecting; sync(); }) : null;
  if (io) io.observe(cv);
  document.addEventListener("visibilitychange", sync);
  if (mq.addEventListener) mq.addEventListener("change", sync);

  root.appendChild(cv);
  applySize();
  sync();

  return {
    set: function (n) {
      if (n.c1 || n.c2) { TH.c1 = n.c1 || TH.c1; TH.c2 = n.c2 || TH.c2; TH.v++; }
      if (n.speed != null) o.speed = n.speed;
      if (n.size != null && n.size !== o.size) { o.size = n.size; applySize(); }
      if (mq.matches) draw(VT, 0);
    },
    destroy: function () {
      stop();
      if (io) io.disconnect();
      document.removeEventListener("visibilitychange", sync);
      if (mq.removeEventListener) mq.removeEventListener("change", sync);
      if (cv.parentNode) cv.parentNode.removeChild(cv);
    }
  };
}

omtLoader(document.getElementById("omt-loader"), OMT_SPEC, { c1: "#2979FF", c2: "#FF9100", speed: 1, size: 160 });
</script>
158 行

背后的数学

中点位移法,偏移量与线段长度成正比,得到分形闪电主干;分叉递归并减少细分次数。

署名

按 CC BY 4.0 免费用于个人与商业项目。请保留代码开头的注释,或用一个可见链接署名作者。

Loader animation by onemilliontools.com: <a href="https://loading.onemilliontools.com/loaders/lightning">onemilliontools.com</a>

授权