critter-fx
v0.1.0
Published
Canvas critters for the browser: bats, birds, bugs and anything else that moves on its own, with flocking, roosting and pointer scatter. No dependencies.
Maintainers
Readme
critter-fx

Critters for the web: bats, crows, owls, moths, bees, ghosts, fish, spiders and a few things that are not critters at all (balloons, lanterns, a witch, a sleigh) that fly by, roost, swarm, wander, crawl and scatter. One file, no dependencies, canvas rendered.
<script src="critter.js"></script>
<script>Critters.start('bats');</script>That is the whole setup. Everything below is optional.
Live demo - every option has a control, down to each key a kind can carry, and it prints the Critters.start() call for whatever you set, so it doubles as a config builder. It is demo.html from the repo, so cloning and opening it locally gets you the same page.
Made for the Halloween theme on dbd-randomizer.com, but built as its own library from the start, with nothing in it tied to that site, so it works on any page. It shares its approach with snow-fx.
Early build. The API is not stable yet, so expect some of it to change before 1.0.
How it works
Every critter is a slot in a fixed pool of typed arrays, and every frame of every kind is drawn once into a sprite atlas, so a scalloped bat wing costs the same per frame as a dot. The art is hand-drawn SVG path data, with the wings generated per frame so the flap is smooth. The loop stops outright while the tab is hidden, and a governor sheds critters on weak hardware instead of stuttering.
Install
Download critter.js and drop it in, or pull it from npm:
npm install critter-fx<script src="https://unpkg.com/critter-fx"></script>A script tag attaches window.Critters, and the same object comes back from require('critter-fx'). No build step either way.
Usage
Critters.start(); // bats flying by and roosting on the top edge
Critters.start('colony'); // a preset
Critters.start({kinds: 'moth', modes: 'orbit'}); // moths circling the pointerEverything is live. Change options while it is running and the field picks them up straight away, no restart:
Critters.set({count: 20, modes: {swarm: 2, roost: 1}});Several effects at once, each with its own canvas and its own options:
const bats = Critters.create('bats');
const fireflies = Critters.create({kinds: 'firefly', modes: 'wander', count: 30});
bats.start();
fireflies.start();Kinds
A kind is what a critter looks like and how it moves: atlas frames plus a gait.
| Kind | Gait | Perches |
|---|---|---|
| bat | fast erratic flap, banks into turns | hangs upside down |
| crow | flap then glide, side on, faces where it flies | stands |
| moth | quick flutter, jittery, heads where it flies | stands, wings folded |
| ghost | floats, bobs and fades in and out | no |
| butterfly | slow flutter, wanders | stands, wings closed |
| firefly | glow that blinks, drawn additively | no |
| owl | slow flap and long glides, seen from the front | stands |
| bird | small songbird, quick flaps between short glides, side on | stands |
| gull | the distant M shape, mostly gliding | no |
| bee | blurred wings, jittery, heads where it flies | no |
| dragonfly | hovers, then dashes (dart) | no |
| fish | swims side on with a swishing tail, three colours by default | no |
| jellyfish | pulses, bobs and fades | no |
| wisp | a flickering flame of light, drawn additively | no |
| spider | never flies: walks the perch line, drops on a thread, spins webs | crawls, see below |
| balloon | drifts and tilts, string trailing, five colours by default | no |
| lantern | paper sky lantern with a flickering glow | no |
| witch | on a broom, cape flapping, side on | no |
| sleigh | two reindeer and a loaded sleigh, side on | no |
| plane | paper plane, side on | no |
| image | your own art, a single image or a horizontal strip of frames | if you give it perch |
kinds takes a name, a list of names, or a list of objects with a weight:
Critters.set({kinds: 'bat'});
Critters.set({kinds: ['bat', 'ghost']});
Critters.set({kinds: [{type: 'bat', weight: 3}, {type: 'crow', weight: 1, size: [40, 70]}]});Any kind entry can override these keys for itself:
| Key | Effect |
|---|---|
| weight | Share of the field, relative to the other kinds. Rounded to a whole number of at least 1. |
| size | Drawn size in px, [min, max]. Depth picks where in the range each one falls. |
| speed | Cruising speed in px/sec. |
| opacity | Alpha range. |
| flap | Wing beats per second (the hem wave for ghosts, the blink rate for fireflies). |
| colour / accent | Body colour, and the colour of eyes, markings or wing edges. colour also takes a list, and each critter of that kind picks one: {type: 'balloon', colour: ['#e33', '#3ae', '#fc3']}. Every colour is its own set of atlas cells. |
| spot | A third colour where the art has one: butterfly wing spots, the songbird's breast, insect wings, the spider's mark. |
| glow | Halo colour baked into the sprite, or null. |
| frames | Frames in the flap cycle. More is smoother and costs atlas memory, not frame time. |
| turn | Steering acceleration in px/sec², how agile it is. |
| jitter | Size of the random kicks that make bats and moths look erratic. |
| minSpeed | Fraction of cruising speed it never drops under. Bats cannot hover, ghosts can. |
| glide | Seconds of gliding between spells of flapping, [min, max], or null to flap all the time. |
| dart | Seconds spent hovering between dashes, [min, max], or null. The dragonfly gait. |
| bob / fade / blink | Vertical bob in px, how far the alpha dips as it drifts (0 to 1), and the lit fraction of each blink cycle. |
| crawl | true makes the kind a crawler: it lives on the perch line instead of flying. |
| from | Which edges it enters from: any, sides, ends, one of left, right, top, bottom, or a list of those. Most kinds are any; side on kinds are sides, balloons and lanterns bottom, the paper plane the sides and the top. |
| turnRate | Radians per second it can turn. Set, the kind steers by heading: it comes round in an arc and cannot stop or reverse. Crows, owls, gulls, the witch, the sleigh and the plane. |
| sink | Makes a turnRate kind an unpowered glider, in px/sec². Level flight loses speed, a turn costs more, and at minSpeed it stalls and the nose drops until it has speed again. The paper plane. |
| rise | Buoyancy, as a fraction of cruising speed. It climbs while it wanders, leaves by the top and comes back in from its from edge. Balloons and lanterns. |
| level | 0 to 1, how much it refuses to climb or dive. Fish, the witch, the sleigh. |
| surge | 0 to 1, how much of its speed comes in pulses on the beat. Jellyfish, and a little for fish. |
| bobRate | How fast bob goes, in radians per second, separate from flap. |
| tilt | For side, the steepest it pitches, in radians. |
| skittish | How much the pointer bothers it: scales scatter.radius, roost.wake and the reach of a scare. 0 is never scared, by the pointer, a click or scare(). Lanterns, balloons, jellyfish, the witch, the sleigh and the plane are 0. |
| reaction | What it does when the pointer is inside the flee radius: flee, curious (comes over and hangs about, fireflies and wisps) or freeze. It holds in every mode: a curious kind breaks off a flyby or leaves its perch to come and look, then carries on, and a frozen one stays on its perch. A click and scare() still send anything skittish off. |
| flees / chases | Lists of other kinds it gets away from or goes after. Bats chase moths, songbirds chase butterflies, bees and dragonflies and flee owls. A catch sends the prey fleeing and fires catch; nothing is removed. |
| sense | How far away it notices the kinds it chases or flees, in px. 160 unless the kind says otherwise. |
| lure | How hard attractTo elements pull on it. Moths 1.6, most kinds 1, the things 0. |
| flapBurst | For a kind that glides, seconds of flapping between glides, [min, max]. |
| modes | The modes this kind will take, as a list. A witch or a sleigh is ['flyby'], so in a mixed field they never end up wandering. If nobody in the mix takes a mode, everybody does. |
| flyby / roost / scatter / wander / swarm / follow / orbit | The kind's own copy of those option groups. {type: 'crow', flyby: {group: [4, 7]}, roost: {wake: 300}}. What it leaves out comes from the instance. Honoured keys: flyby.interval, group, curve, wobble; roost.where, sides, wake, away, restless, drop, web, webSize; scatter.strength, flee; wander.drift, margin; swarm.radius, cohesion, alignment, separation; follow.distance, spread; orbit.speed. |
| blend | source-over, or lighter to draw it additively, which is what makes fireflies and wisps glow. |
| silk | Colour of a crawler's thread and web. |
| orient | bank tilts into the direction of travel, side flips to face it, heading rotates to point along it, none stays upright. |
| bank | Largest bank angle in radians, for bank. |
| perch | hang, stand or null: how the perched art is drawn, hanging below its anchor or standing above it. |
| poses | The holds it has perched art for. Left out, it is just perch. art is called once per pose with the hold's name as perched, and a cling pose is drawn against a wall on its left: the library mirrors it for the other wall, so the head stays up. Moth and butterfly have ['stand', 'cling'], spider ['hang', 'stand', 'cling']. |
| holds | The holds it will take, any of hang (under something), stand (on top of something) and cling (on a wall). Left out, it is whatever perch is. A hold with no pose behind it is ignored, so nothing is ever shown in a pose borrowed from another hold. |
| anchor | Where the art touches the surface, in the 100 box: the y of the feet for hang and stand, the x of the wall for cling. A number, or one per pose: {stand: 78, cling: 49}. |
| src / frames / perchFrame | image only: the image URL, how many frames it holds side by side, and which one to show while perched. Loads cross-origin anonymous, so the host has to allow it. |
Critters.kind('bat') returns a kind's full definition.
Your own kinds
A kind is the whole definition in one place: its art, its gait and its own behaviour. registerKind adds one for every instance, and extends starts from an existing kind.
Critters.registerKind('albino', {extends: 'bat', colour: '#f2f0ea', skittish: 2});
Critters.registerKind('parrot', {extends: 'bird', src: 'parrot-strip.png', frames: 6});
Critters.registerKind('orb', {
size: [10, 20], speed: [20, 40], flap: 1, rise: 0.5, from: 'bottom', skittish: 0,
art(ctx, spec, frame, frames, perched) {
ctx.fillStyle = spec.colour;
ctx.beginPath();
ctx.arc(50, 50, 30 + 6 * Math.sin((frame / frames) * Math.PI * 2), 0, Math.PI * 2);
ctx.fill();
},
});
Critters.start({kinds: ['albino', 'orb']});art draws one frame into a 100 by 100 box and is called once per frame when the atlas is painted, never while running. Side on art faces right, heading art faces up. A kind with no art of its own, and none inherited, is drawn from src like image.
Modes
A mode is what a critter is doing. Give modes a name, a list, or weights, and each critter takes one, spread evenly through the pool.
Critters.set({modes: 'swarm'});
Critters.set({modes: {flyby: 3, roost: 2}});| Mode | Behaviour |
|---|---|
| flyby | Off screen until its interval runs out, then across on a curved path in a small group, then gone again. |
| roost | Perches on the edges of the field, on the elements matched by roostOn, or on both. Takes off when the pointer comes near, flies around for a while, then lands again. |
| swarm | A colony flocking together (cohesion, alignment, separation) around a point that drifts across the screen. |
| wander | Slow ambient drift, each critter on its own path. |
| follow | Trails the pointer at a distance. Wanders while the pointer is away. |
| orbit | Circles the pointer, a point or an element. Moth to a flame. |
| scatter | Not a mode of its own: in a modes list it switches scatter.enabled on. |
Roosting needs a kind that perches, and every kind only takes the holds it can manage:
| Hold | Where it is | Who takes it |
|---|---|---|
| hang | under an element, or the top edge of the field | bat, spider |
| stand | on top of an element, or the bottom edge of the field | crow, owl, bird, moth, butterfly, spider |
| cling | the left and right sides of an element, or of the field | moth, butterfly, spider |
A kind only takes a hold it has a pose for, so nothing is ever shown hanging, standing or clinging in a way it was not drawn. holds on a kind narrows it further: {type: 'spider', holds: ['hang']} keeps spiders on their threads.
So a mixed field sorts itself out: bats hang under a heading while crows stand on it and butterflies sit on its sides. roost.sides narrows which edges are on offer and roost.where picks between the field, the elements and both. Neither can hand a kind a hold it does not have, and a kind with nowhere to perch flies around looking instead.
Both can be set per kind as well, which is how one kind keeps to the window while another takes the elements:
Critters.start({
kinds: [{type: 'bat', roost: {where: 'window'}}, {type: 'butterfly', roost: {sides: ['left', 'right']}}],
modes: 'roost',
roostOn: '.card h3',
});Crawlers
A spider (or any kind given crawl: true) never flies, whatever mode its slot has. It lives on its perches: hanging under an edge, standing on top of one or clinging to a side, on the field or on the elements matched by roostOn.
- In
roostit either drops on a thread (roost.droppx) and hangs there, or spins a web under the edge and sits in the middle of it (roost.webis the chance,roost.webSizethe size). When the pointer comes withinroost.wake, or on a scare, it climbs back up, walks along the edge to another free perch and settles again. A deserted web fades. Threads and webs need room to hang, so they only happen under an edge. On top of something or on a side it is drawn side on, feet to the surface, and walks along it when it moves on. - In any other mode it patrols: waits on the edge for a few seconds, walks to another perch, waits again.
A crawler only walks along the side it is on, and does not turn the corner. burst() skips crawlers.
Presets
Critters.start('colony');
Critters.preset('ghosts');
Critters.registerPreset('mine', {kinds: 'bat', modes: 'swarm', count: 20});Built in: bats, colony, belfry, crows, moths, ghosts, butterflies, fireflies, haunted, owls, songbirds, gulls, bees, dragonflies, meadow, school, reef, jellyfish, wisps, spiders, webs, balloons, lanterns, witches, sleigh, planes.
A preset is mostly a choice of kind: what a balloon or a sleigh does is part of the kind itself, see below.
Options
Every range accepts a single number or a [min, max] pair. All of them can be changed live with set().
Scene
| Option | Default | Effect |
|---|---|---|
| bounds | null | Element or selector to fill. null is the viewport. |
| zIndex | 9000 | Stacking of the canvas. |
| className | '' | Extra class on the canvas. |
Field
| Option | Default | Effect |
|---|---|---|
| kinds | [{type: 'bat', weight: 1}] | Weighted mix of kinds, see above. |
| modes | {flyby: 3, roost: 2} | Weighted mix of modes, see above. |
| count | 10 | How many critters. Sizes the pool. |
| intensity | 1 | Multiplier on count. |
| size | null | Overrides every kind's size range. |
| speed | null | Overrides every kind's speed range. |
| sizeScale | 1 | Multiplier on every kind's size, whatever set it. 2 is twice as big without having to know the kind's own range. |
| speedScale | 1 | The same for cruising speed. |
| opacity | [0.8, 1] | Alpha range. |
| depth | 0.5 | 0 to 1. How much smaller critters also fly slower and fainter, so they read as further away. |
| colour | null | Overrides every kind's body colour. |
| glow | null | Halo colour on every kind, useful for dark kinds on a dark page. |
Behaviour
| Option | Default | Effect |
|---|---|---|
| flyby | {interval: [2, 8], group: [1, 3], from: 'auto', curve: 0.3, wobble: 16} | Seconds between passes, how many cross together, which edges they come from, how much the path bends, and the side to side wobble in px. from is auto (each kind uses its own from), or any, sides, ends, left, right, top, bottom to force one on everything. |
| roostOn | null | Selector, element or list of elements to roost on. Hanging kinds hang beneath them, standing kinds stand on top, clinging kinds take the sides. null uses the edges of the field. |
| roost | {where: 'auto', sides: ['top', 'bottom', 'left', 'right'], spacing: 40, wake: 120, away: [4, 10], restless: 0.02, remeasure: 500, drop: [20, 140], web: 0.35, webSize: [70, 120]} | where is auto (the roostOn elements when they match something, otherwise the field), window, elements or both. sides is which edges of those are offered, one name or a list. Then px between perches, how close the pointer gets before one takes off (0 never), seconds spent flying before landing again, chance per second of taking off unprompted, and ms between perch remeasures for layout that moves without a scroll or resize. For crawlers: how far a thread drops in px, the chance a roosting spider spins a web instead (0 to 1), and the web size in px. |
| swarm | {max: 60, radius: 90, cohesion: 1, alignment: 1, separation: 1.2, roam: 0.4, follow: false, margin: 80} | Most critters allowed to swarm (the rest wander, since flocking is O(n²)), neighbour radius in px, the three flocking weights, how far the flock roams from the centre (0 to 1), whether it chases the pointer instead, and the soft edge margin. |
| wander | {drift: 1, margin: 60} | Speed of the wandering paths, and the soft edge margin. |
| attractTo | null | Selector, element or list (16 at most) that pulls in whatever comes within reach, in any mode. Each kind's lure says how much it cares. |
| attract | {radius: 280, strength: 0.6} | How far away an attractor is noticed, in px, and how hard it pulls. |
| avoidOn | null | Selector, element or list (16 at most) that critters steer out of. Flyby paths ignore it. |
| avoid | {margin: 24, strength: 1.5} | Extra px kept clear round each avoided element, and how hard it pushes. |
| follow | {distance: 80, spread: 60} | How far behind the pointer they trail, and how widely they spread around that point. |
| orbit | {target: 'pointer', radius: [50, 120], speed: 1.4} | What to circle ('pointer', [x, y] in page coordinates, or an element or selector), the radius in px, and radians per second. |
| scatter | {enabled: true, radius: 110, strength: 1, click: true, clickRadius: 240, flee: [0.8, 1.6], ignore: 'a, button, input, select, textarea, label, [data-critters-ignore]'} | Flee the pointer within radius, how fast they flee, whether a click anywhere calls scare(), its radius, and how many seconds a scare lasts. Follow and orbit ignore the pointer distance, since they are drawn to it, but still flee a click. A click on anything matching ignore does not scare. |
| burst | {max: 24, count: 10, speed: [200, 340], spread: 360, direction: 0, kind: null} | Slots kept for bursts, and the defaults for burst(): how many, launch speed, the cone in degrees, its direction (0 up, 90 right), and which kind (null uses the mix; any other has to be a flying kind already in kinds). |
Lifecycle and performance
| Option | Default | Effect |
|---|---|---|
| fadeIn / fadeOut | 800 / 600 | Canvas fade in ms. |
| pauseWhenHidden | true | Cancels the loop entirely while the tab is hidden. |
| pauseOnBlur | false | Same when the window loses focus. |
| respectReducedMotion | true | start() becomes a no-op and emits blocked when the user asks for reduced motion. |
| tier | 'auto' | auto, low, medium or high. Caps count, DPR and glow. |
| maxDpr | 2 | Upper bound on device pixel ratio. |
| targetFps | 50 | What the governor aims for. |
| autoDegrade | true | Sheds critters when frames run long, creeps them back when they recover. |
| debug | false | On-canvas fps, counts and perch readout. |
API
Critters.start(options|presetName) // options accumulate across runs
Critters.stop({fade: false})
Critters.toggle()
Critters.pause() / Critters.resume()
Critters.set({count: 20}) // live, any subset, nested objects merge
Critters.get() / Critters.get('modes')
Critters.reset() // back to defaults
Critters.preset(name, overrides)
Critters.registerPreset(name, options)
Critters.registerKind(name, definition) // a new kind: spec keys, plus art() and/or extends
Critters.kind(name) // a kind's full definition, or null
Critters.setDefaults(options) // changes what start() and reset() build from, for every instance
Critters.burst(x, y, options) // or burst(element|selector, options)
Critters.scare(x, y, radius) // page coordinates, radius defaults to scatter.clickRadius
Critters.refresh() // re-reads roostOn, for when matching elements were added
Critters.create(options|presetName) // an independent instance with this same API
Critters.state()
Critters.on(event, fn) / Critters.off(event, fn)
Critters.destroy()
Critters.running // boolean
Critters.presets // array of names
Critters.kinds // array of kind namesEverything except get() and state() returns the instance, so calls chain. state() reports running, paused, tier, fps, critters, requested, degradeScale, reducedMotion, plus how many are flying, perched, fleeing, crawling and waiting off screen, how many are bursting, how many usable perches there are, the swarm size, and mix, the live count of each kind.
Events
| Event | Payload | Fires |
|---|---|---|
| start | {tier, critters} | The field is up and the first frame is scheduled. |
| stop | {} | Once the fade out finishes and the canvas is gone. |
| pause / resume | {} | Manual calls. |
| degrade | {fps, scale, live} | The governor has shed or restored critters. |
| tick | {dt, fps} | Every frame, and only measured when something is listening. |
| blocked | {reason} | start() refused. Currently only 'reduced-motion'. |
| burst | {x, y, count} | burst() launched, with how many it actually had room for. |
| scare | {x, y, radius, count} | A click or scare(), with how many it reached. |
| takeoff / land | {x, y} | A roosting critter left or reached its perch. |
| catch | {x, y, hunter, prey} | A kind caught one it chases. hunter and prey are kind names. |
Notes
- The canvas is fixed and the page scrolls under it, so element perches are remeasured on scroll (once per frame at most), on resize, and every
roost.remeasurems. A perch that scrolls out of view lets its critter go, and it comes back once there is a perch to land on. - Bats, crows, spiders, the witch and the sleigh are near black. On a dark page give them a
glow, or a lightercolour. - Sprites are painted once into 128px cells, so anything drawn much over 128px (a large sleigh on a dense display) starts to soften.
- Swarm cost grows with the square of its size. 60 is comfortable; past a few hundred it needs the spatial grid that is not written yet.
- Scoping to an element adds
position: relativeto it when it is currentlystatic.
Contributing
Issues and pull requests welcome. npm test has to pass: it drives real frames against a stubbed canvas, so it catches state bugs and says nothing at all about how the thing looks. Anything visual means opening demo.html in a real browser.
License
MIT, see LICENSE.
