All loaders

18

Starling Flock

Thirty-four birds follow three simple rules and flock by themselves.

  • Biomimetic
  • Cycle 4s
  • Canvas, uses a small inline script
  • No dependencies

Customize

Palette
Preview background

Code

<!--
  "Starling Flock" loader by onemilliontools.com
  https://loading.onemilliontools.com/loaders/starling-flock
  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: "Starling Flock",
  create(g) {
    const { x, dot, P, TAU } = g;
    const N = 34, B = [];
    // start from a stable, already-flocking state so the first frame is never a random scatter
    for (let i = 0; i < N; i++) { const a = Math.random() * TAU; B.push({ x: 48 + (Math.random() - .5) * 34, y: 48 + (Math.random() - .5) * 34, vx: Math.cos(a), vy: Math.sin(a) }); }
    let acc = 0;
    function step() {
      B.forEach(b => {
        let sx = 0, sy = 0, ax = 0, ay = 0, cx = 0, cy = 0, n = 0;
        B.forEach(o => {
          if (o === b) return;
          const dx = o.x - b.x, dy = o.y - b.y, d2 = dx * dx + dy * dy;
          if (d2 < 484) { n++; ax += o.vx; ay += o.vy; cx += o.x; cy += o.y; if (d2 < 49) { sx -= dx; sy -= dy; } }
        });
        // three rules: align with neighbours, move toward their centre, keep a little apart
        if (n) { b.vx += (ax / n - b.vx) * .05 + (cx / n - b.x) * .004 + sx * .03; b.vy += (ay / n - b.vy) * .05 + (cy / n - b.y) * .004 + sy * .03; }
        const dd = Math.hypot(b.x - 48, b.y - 48);
        if (dd > 30) { b.vx -= (b.x - 48) / dd * .07; b.vy -= (b.y - 48) / dd * .07; }
        const sp = Math.hypot(b.vx, b.vy), k = sp > 1.2 ? 1.2 / sp : sp < .7 ? .7 / (sp || 1) : 1;
        b.vx *= k; b.vy *= k;
      });
      B.forEach(b => { b.x += b.vx; b.y += b.vy; });
    }
    return function (t, dt) {
      // the flock is a simulation, so it advances by elapsed time: 1 step = 16.7 ms at speed 1
      acc += dt / 16.67;
      let n = Math.min(4, Math.floor(acc)); acc -= Math.floor(acc);
      while (n-- > 0) step();
      const col = P(8);
      x.clearRect(0, 0, 96, 96); x.lineCap = "round"; x.lineWidth = 1.7;
      B.forEach(b => {
        const c = col[Math.floor((Math.atan2(b.vy, b.vx) + Math.PI) / TAU * 8) % 8];
        x.globalAlpha = .85; x.strokeStyle = c; x.beginPath(); x.moveTo(b.x, b.y); x.lineTo(b.x - b.vx * 4, b.y - b.vy * 4); x.stroke();
        dot(x, b.x, b.y, 1.5, c, 1);
      });
      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>
130 lines

The math

Boids: separation, alignment, cohesion. Speed is clamped to 0.7–1.2 and a soft wall keeps the flock in the frame. It is a live simulation, so no two runs match.

Attribution

Free for personal and commercial use under CC BY 4.0. Keep the comment at the top of the snippet, or credit the author with a visible link.

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

License