Flocking · How it works & code
Boids: Separation, Alignment, and Cohesion Rules.
Runtime logic
Visiting `/canvas/flock`, DemoHost lazy-loads `demos/kits/kit-canvas.js` (registry `mod: 'kit-canvas'`) and calls `mount(host, { variant: 'flock' })`. mount resolves the variant to family `flock`; `withControls` builds the control panel (6 presets + sliders). `createCanvasStage` creates the `<canvas>` (HiDPI ≤ 2×, ResizeObserver) and the info panel. The family’s `build(S)` initialises state and returns the per-frame callback. Every `requestAnimationFrame`: read controls, advance a speed-scaled clock (dt ≤ 50 ms), run the frame callback; returned readouts go to the info panel. Changing parameters: colour/speed/size apply live; structural ones remount; leaving the page cancels rAF, removes listeners and frees resources.
Environment
Canvas 2D: 2D canvas drawing; requestAnimationFrame: Display-synced animation loop; ResizeObserver: Canvas follows container size; Pointer Events: Unified mouse/touch/pen events; devicePixelRatio: Crisp HiDPI rendering (capped at 2×) · react 18.3.1, react-router-dom 6.30.6, vite 5.4.21
Dependencies
react 18.3.1
Imported APIs
withControls — Wraps the demo in the shared control panel (presets, sliders, reset); hot-updates or remounts on change; paramsFromSpec — Turns the spec (colour/speed/size/count/extras) into control-panel parameter definitions; createCanvasStage — Shared Canvas 2D stage: canvas + info panel, HiDPI, one rAF loop, pointer state, idle auto-pointer; rng — Seeded deterministic PRNG (same seed, same result); hexRgb — Colour string → [r, g, b]; rgba — Builds an rgba() colour string; clamp — Clamps a value to a range; TAU — Constant 2π; fmt — Number formatting (fixed decimals); F — Formula block HTML; S.clear — Clears with the background colour (translucent = trails); S.get — Reads current control values; S.onFrame — Registers a per-frame callback; its return value feeds the info panel; ctx.beginPath() — Starts a new path; ctx.moveTo() — Moves the pen without drawing; ctx.lineTo() — Adds a straight line to a point; ctx.closePath() — Closes the current sub-path; ctx.fill() — Fills the current path; ctx.arc() — Adds a circular arc (center, radius, start/end angle); ctx.stroke() — Strokes the current path
Source code
frontend/src/demos/kits/kit-canvas.js: FAM.flock (L492-L543)
Code walkthrough
L494-494: Control definitions (colour/speed/size/count/extras): Individual Color, Individual Size, Number of Individuals N, Separation Weight, Alignment Weight, Cohesion Weight. L495-495: Preset buttons: name → parameter overrides (6). L496-504: Info-panel content: live rows(v), formula, notes, params, steps. L505-542: Init function: sets up state and returns the per-frame callback: draws with Canvas 2D `beginPath`, `moveTo`, `lineTo`, `closePath`, `fill`, `arc` …; math via `Math.round`, `Math.cos`, `Math.sin`, `Math.hypot`; returns readouts `n`, `vm`, `pol`, `nb`, `fl`, `ws`, `wa` … to the info panel.
Principles
a = w Split · Σ(p − pⱼ)/r² + w Right · (v̄邻 − v) + w Assemble · (p̄邻 − p) Speed limit 40 GH |v| ≤ 110 px / s Polarization φ = |Σ v̂ᵢ| / N (1 = Exactly the same 1986 年 Reynolds Discovery: Each bird only looks Nearby 50px Inner And by following the three rules, our fellow citizens will be able to emerge from a veritable group movement: ① Separated : And push away too close;② Align : (b) The direction is closer to the average of the neighbours;③ Bring together : To the center of the neighbour. Haven't“Headbird”,The whole pattern is the result of purely local rules. Polarization φ 衡量大家方向一致的程度。打开捕食者后,靠近指针的个体会逃开。