Skip to content

pixi-hm05 ​

A pixi.js v8 player for timeline animations exported as one JSON file plus texture-atlas PNG pages — the successor of pixi-mc. This package loads an export and plays its movie clips with a familiar timeline API.

bash
npm install pixi-hm05 pixi.js pixi-filters
ts
import { Application } from "pixi.js";
import { Asset } from "pixi-hm05";

const app = new Application();
await app.init({ width: 960, height: 540 });
document.body.appendChild(app.canvas);

const asset = await Asset.load("hero/hero.json"); // + its atlas pages
const hero = asset.create();          // the main timeline
app.stage.addChild(hero);             // top-level clips tick by themselves
hero.timeline.gotoAndPlay("walk");

Without a bundler, use the UMD build (dist/pixi-hm05.umd.cjs, global PixiHm05) after pixi.js's own UMD build (global PIXI) and, when the animation uses filters, pixi-filters' browser build (global PIXI.filters).

Exporting ​

File → Export…, format Animation for pixi-hm05 (JSON + atlas). Choose the root timeline (whole stage) or one symbol, and the resolution (texture pixels per document unit). The ZIP holds <name>.json and <name>_<n>.png; keep them together.

Asset ​

Asset.load(url)fetches and validates the JSON, loads the atlas pages and the fonts its texts use, relative to it
Asset.createLoaderContainer(url, {symbol?, onLoad?, …})a LoaderContainer to add to the stage at once; the clip goes into it when loaded (container.loaded → the clip, container.clip)
new Asset(file, pages)from an already parsed file and page textures
asset.create(symbol?)a new SymbolInstance (default: the main symbol)
asset.symbolNamesevery symbol in the export
asset.filethe parsed export (AnimFile, typed)

SymbolInstance (a pixi Container) ​

The timeline inside a symbol is clip.timeline (Timeline): the classic movie-clip API. Frame numbers are the ones the editor's timeline shows: they count from the symbol's First frame setting (clip.timeline.frameBase, 1 unless the symbol is set to 0; the main timeline always 1) — currentFrame, labels and events too. One argument = a label (of the current section first) or a frame number of the current scene; two arguments = a section, then a label / a frame counted from the section's first frame / Timeline.START / Timeline.END. A scene is never an argument: scene(name) before the goto. The control methods return a chain: each call waits until a playTo before it has arrived (or a wait is over); if anything else moves the playhead first, the rest is dropped.

ts
clip.timeline.scene("s1").goto("walk", 0).playTo(Timeline.END).gotoAndPlay("stand", 0);
clip.scene("s1").goto("walk", 0);   // the same chain starters on the clip itself

When a playTo arrives with more of the chain waiting, its frame is shown for one frame time before the chain goes on. Frames a playTo passes run no actions.

clip.timeline.
play() / stop()
stopAll()stops this timeline and every clip nested inside it (synced clips follow their stopped parent)
goto(a, b?) / gotoAndPlay(a, b?) / gotoAndStop(a, b?) / playTo(a, b?)goto* jump at once; playTo never plays into another section
gotoAfter(a, b?) / gotoAndPlayAfter(a, b?) / gotoAndStopAfter(a, b?)the same jump, but once the playhead leaves the current frame (shown for its time first); another move cancels it
scene(name), wait(s), then(fn) (on the chain)chain steps
nextFrame() / prevFrame() / nextScene() / prevScene()
currentFrame, totalFrames, currentLabel, currentScene, currentSection, labels, scenes, sections, isPlayingread-only state
fps (default: the export's), speed (rate multiplier), loop (default true), setFps / setGlobalFps / resetFps / resetGlobalFps, setDirection, waitplayback
positionthe playhead with its fraction (a speed that is not whole puts it between frames); setting it = a goto
showSection(section, phase?, progress)stop at progress 0..1 of the way through a section — or one phase of it (from a label to the next label of the section) — drawn at the fractional position; for games that decide each tick how far an action is
playSection(section, seconds, {phase, from, to, loop}), playSteps([{section, phase?, from?, to?, seconds}], {loop}), stopSteps(), stepsPausedplay a section through in a set time whatever its frame count; resolves true at the end, false when stopped or when anything else moves the playhead

On the clip itself:

clip.
smooth (default: the export's smooth), subframe (0..1), inSubframedraw tweens between frames at the screen's rate; subframe = how far the drawing is past the current (real) frame, 0 = a real frame
autoUpdatetop-level clips follow Ticker.shared; set false and call update(deltaMS) yourself
slotsdress-up by name: slots.use(profile, match?), remove, clear, rules (see "Slots")
findText(path)a live text by instance name ("score", or "hud.score" through named clips), or null
find(path)a clip by target path (_parent, _root, _top, _children[n], names)
releaseProps(...names)values a script set (x, y, scale, rotation, skew, alpha, blendMode, filters) win over the timeline until handed back here
setFilters(list), setColorEffect([8])the editor's filters / Flash colour transform, script-owned
brightness, setTint(color, amount)Flash Brightness (-1..1) / Tint as the clip's colour effect (script-owned like setColorEffect; NOT pixi's multiplying tint)
addLook(name, look), removeLook(name), clearLooks(), hasLook(name), lookNamesstacked looks ON TOP of the timeline's (see below)
getScript(cls | id), getScripts(), send(method, ...args)its Behaviours
hitTestPoint(x, y, exact?), hitTestObject(o), getObjectsUnderPoint(x, y)hits on drawn pixels

Live text (TextObject) ​

Text is not baked into the atlas: each text object of the export is an TextObject (a pixi Container) drawn from file.texts. text.text = "120" changes the characters (rich styling is dropped: the base font applies); text.def is the full definition (font, box, alignment, vertical writing …) — assign a changed copy to restyle. After a script wrote either, the timeline no longer changes that text. Text published with "Export as bitmap" is a plain sprite.

Scripts (Behaviour) ​

A script's default export extends Behaviour; symbols, scenes and instances bind them (one object per bound clip). Hooks (Flash names): onCreate, onAddToStage, onEnterFrame / onExitFrame (every frame, also while stopped, around the frame's actions), onUpdate(dt), onRemoveFromStage, onDestroy, onResize(w, h); this.clip, this.timeline, this.fields (static fields defaults, then the symbol's / instance's values). A published bundle registers its classes with defineScripts(scriptsId, {id: Class}); asset.bind(path, Class) does it by hand. A playback call action runs a method of one.

Camera ​

A main timeline is framed by its camera (the editor's camera layer: pan, zoom, turn, canned motions; layers pinned to the camera stay on the frame); play() makes the page the camera frame's size. Scripts move it in stage units — a value set wins over the timeline until released:

ts
const cam = this.camera!;            // = this.clip.camera (null: a symbol played alone)
cam.zoom = 2; cam.angle = 10;        // x, y, zoom, rotation (rad) / angle (deg)
cam.follow(this.clip.find("hero"), { lerp: 0.15, deadzone: { width: 80, height: 40 }, bounds: { x: 0, y: 0, width: 2400, height: 600 } });
cam.release("zoom");                 // back to the timeline (none = all)
const p = cam.frameToStage({ x: e.global.x, y: e.global.y }); // view pixels → stage

A main timeline without a camera layer still has a camera (stage centre, not zoomed), so scripts can scroll any stage.

Stage anchors (any page size) ​

Layers the editor anchored to the stage edges (AnimLayer.an: left / centre / right / stretch × top / middle / bottom / stretch) keep to the VIEW's edges. play() fills the page (no letterbox) and tells the clip the view on every resize; size it yourself with r.resize(w, h). A clip in your own pixi app: give it the visible part of the stage's space —

ts
import { stageFit } from "pixi-hm05"; // anim-format's THE page layout
const { k, view } = stageFit({ width: 800, height: 450 }, app.screen, "fit", "center");
clip.scale.set(k); clip.position.set(-view.x * k, -view.y * k);
clip.setStageView(view);              // null = as authored

Loading another published file ​

await Asset.load(url, { scripts: true, onProgress }) — JSON, pages, fonts and its scripts bundle; the same URL gives the same asset; asset.create("ScriptID"); asset.unload() frees it. Asset.createLoaderContainer(url, { symbol, onLoad }) gives a container to place right away; the clip is added to it once loaded. Inside it _root is its own main timeline, _top the page's.

Events (pixi EventEmitter, on clip.timeline):

"frame" (frame, clip)entered a frame (real frames only — never an in-between drawn by smooth)
"complete" (clip)reached the end without looping
"arrived" (clip)a playTo reached its frame

Playback actions ​

Playback layers in the editor export actions, run in order as a chain when the playhead enters their frame (a playTo / wait holds the rest; a jump back to a frame already visited in the same round by a gotoNow is ignored with a console warning): play, stop, togglePlay, scene, gotoNow (jumps at once) / gotoAfter (the same jump once the playhead leaves this frame; with then: "play" | "stop" = gotoAndPlay / gotoAndStop), playTo (plays forward or backward to a frame and stops; frames passed on the way run no actions), nextFrame / prevFrame, nextScene / prevScene, setFps / resetFps (scope: "global" = every clip without its own speed, "self" = one clip; duration seconds = a linear ramp), stopSounds, playSound / stopSound, setVisible, emit (an event for your game — see below). Most take a target path from the clip that runs them: _parent, _root, _children[n] (n-th child clip, bottom → top), an instance name or id, joined with dots (_parent._children[0].redball). Instances with on actions (click, pointerOver, pointerOut) are interactive; their default target is the instance itself. A parent-synced clip moved by an action from outside (another clip, a click, your code) keeps its own clock from then on; its own frame actions never detach it. A symbol exported with "stop at end" plays once and holds its last frame.

ts
clip.timeline.playTo("intro");   // backward when "intro" is behind
clip.find("_children[0].ball")?.timeline.gotoAndStop(3);
clip.setGlobalFps(12, 2);        // everything slows to 12 fps over 2 s
clip.runActions([{ type: "target", target: "ball" }, { type: "stop" }]);
clip.on("arrived", () => {});     // a playTo reached its frame

More actions: repeat (back to a frame N times, then on), gotoRandom, wait (seconds), setDirection (play backward), and playSound with onEnd actions (run when it played to its end). Triggers may also be keys ("key:Space", by KeyboardEvent.code). Pointer hits are pixel exact (transparent pixels do not count). An instance layer (AnimLayer.inst) keeps one clip for the whole timeline: frames without it only hide it, so its name, state and key triggers live on.

Extra API: playTo, nextScene, prevScene, currentFps, setFps / resetFps, setGlobalFps / resetGlobalFps, wait, setDirection, find(path), parentNode(), childNodes(), runActions(list), and pressKey(code) (module export: run key triggers yourself).

Events to your game (emit) ​

An Emit action in the editor tells your game something happened on a frame — a footstep, the moment a punch starts to count. The player fires it on that clip and the event bubbles up to the clips around it, like a DOM event, so one listener on the character hears every emit inside it.

ts
hero.on("footstep", (e) => {
	e.name;           // "footstep"
	e.value;          // what the action carries: a number, text, JSON or undefined
	e.frame;          // the frame it was emitted on, as that timeline counts
	e.section;        // the section that frame is in, if any
	e.target;         // the clip that emitted it (e.currentTarget = the one hearing it)
	e.stopPropagation(); // no clip further out hears it
});
hero.off("footstep", fn);       // stop listening
hero.emitEvent("hurt", 12);     // say the same thing from your own code

call actions are for Behaviour scripts bound to the symbol; emit is for the game outside.

Nested clips ​

Nested symbols follow their parent's timeline (graphic symbols) with their loop / play-once / single-frame / reverse / speed settings, or keep their own clock when exported as independent (movie clips). Display objects are reused between frames.

Masks ​

Mask layers are exported as layer masks: a masked layer is clipped by the shapes of its mask layer (pixi stencil masks); the mask layer itself is not drawn.

Colour effects ​

Instances with a colour effect (brightness, tint, advanced) carry a colour transform; the player applies it as a pixi ColorMatrixFilter.

Stacked looks ​

clip.addLook("hit", {brightness: 1}) adds a named look over whatever the timeline gives the clip — its colour effect and filters stay. Looks stack in the order added and stay until removeLook(name):

ts
enemy.addLook("poison", { tint: { color: 0x00ff00, amount: 0.4 } });
enemy.addLook("selected", { filters: [{ t: "glow", p: { color: "ffff00", blurX: 8, blurY: 8, strength: 200 } }] });
enemy.addLook("hit", { brightness: 1 });   // a white flash over everything
setTimeout(() => enemy.removeLook("hit"), 100);

A look has alpha (× alpha), brightness (-1..1), tint (a colour, or {color, amount}), colorEffect (Flash Advanced, 8 numbers), adjust (Flash Adjust Color: brightness / contrast / saturation / hue), filters (the editor's catalogue) and blendMode. They are drawn after the timeline's filters: the looks' filters in order, then one colour matrix of every look's colour parts, so a tint covers the glows too. The colour maths are Flash's. Layers have the same (clip.layers.get("arm").addLook(…)), plus setColorEffect([8]), brightness, setTint() instead of the timeline's layer colour (releaseProps("colorEffect")).

Actors: several symbols / sprite sheets as one character ​

ts
import { Actor } from "pixi-hm05";
const hero = new Actor();
hero.addSymbol(bodyAsset, "hero");                     // its sections = actions, labels inside = phases
hero.addSymbol(extraAsset, "hero_more", { prefix: "x_", include: ["dash"] });
hero.addSpriteSheet(sheet, { phases: { kick: { hit: [3, 5] } } }); // a pixi Spritesheet's animations
stage.addChild(hero);
hero.show("jump", "rise", height / maxHeight);         // the game decides how far, every tick
await hero.play([{ section: "walk", seconds: 0.8 }, { section: "jump", seconds: 0.5 }]);

An actor never plays by itself; it shows one part at a time. Options per part: prefix, include, exclude, replace (a later part wins a name clash), matrix. actions() lists action → phases, hasActions({...}) checks a set, currentAction / current.

Overlays: a section on some parts only ​

ts
hero.timeline.playSection("walk", 1, { loop: true });   // the legs walk…
const o = hero.overlay("shoot", { parts: "chest/*" });  // …the upper body shoots, once
await o.done;                                           // true = played to its end
hero.overlay("aim", { parts: ["arm_R/*", "head"], loop: true });
hero.overlay(null, { parts: "arm_R/*" });               // those parts back to the timeline
hero.on("overlayEnd", (e) => console.log(e.value.section));

// a section of ANOTHER symbol, bones / layers paired by name (other pictures)
winter.playShared(boy, "walk", { loop: true });

parts: a bone or layer name ("arm_R"), a branch ("arm_R/*" = the bone, its child bones, the layers following them and the layers parented to those), * globs, "!hand" to leave one out, commas or an array for several; absent = every part. A bone layer's name = all its bones. Hard switch, no blending; overlays stack (the newest wins on a part, the one below shows again when it ends). The overlay's frame actions, sounds and emits do not run. The Playback action "Overlay section on parts" does the same without code.

Filters ​

Instances can carry filters (drop shadow, blur, glow, bevel, gradient glow, gradient bevel, outline, adjust colour, bloom, motion blur, pixelate, RGB split, noise, inner shadow, gradient overlay), drawn after the colour effect, in order. Flash's own (drop shadow, glow, bevel, the gradient ones: blur X / Y, strength %, quality, inner / outer / full, knockout, hide object) and Adjust Color (Flash's colour maths) are this package's own shaders; bloom / outline / motion blur / pixelate / RGB split come from pixi-filters. Tweened filters are baked per frame like everything else. Filter lengths (blur, distance, offsets) are in the units of the clip's parent, so they grow and shrink with the stage scale. createPixiFilter(spec, scale) and applyInstanceFilters(container, specs) are exported for custom use.

Flash's colour maths are exported as plain 20-number pixi ColorMatrix arrays: flashAdjustMatrix({brightness, contrast, saturation, hue}), flashTintMatrix(color, amount), flashBrightnessMatrix(b), multiplyColorMatrix(a, b) (b acts first).

Blend modes ​

Item / layer blend modes are pixi's names plus Flash's invert, layer, alpha and erase, which first draw the object as one group (a filter at the end of its list) — setBlend(container, mode) sets any of them. alpha / erase keep / cut what is under them inside the nearest parent drawn as a group (a layer parent or one with filters, as in Flash), else the whole picture.

Slots (dress-up at run time) ​

A slot profile is the editor's mind map of interchangeable items ("HEAD-front", "HEAD-side", "BODY" …); a profile can be built on another ("Armour" extends "Hero": same names, other pictures). A published file lists the profiles its objects can be dressed from, by their Library names, and clip.slots switches them — the same rules as the editor's dress-up rules:

ts
hero.slots.use("Armour");            // every item Armour has a name for
hero.slots.use("Summer", "HEAD-*");  // only names like HEAD-…, over Armour
hero.slots.rules;                    // [{ profile: "Armour" }, { profile: "Summer", match: "HEAD-*" }]
hero.slots.remove("Summer");         // every rule of Summer (or only one: remove("Summer", "HEAD-*"))
hero.slots.clear();                  // as published
Object.keys(hero.asset.file.slots ?? {}); // the profile names of the file
  • Rules are for the clip and every clip inside it. Later rules win; an outer clip's rules win over an inner clip's. The last rule that matches and has something decides; a profile without the exact name gives its nearest name (HEAD-front → HEAD-default / HEAD), one with nothing of that family leaves the item to the earlier rules.
  • A change shows at once — while playing or stopped — and holds through gotoAndStop. The object keeps its own place, alpha, colour effect, filters, blend and 3D; the two items' pivots line up.
  • use() with a name no profile has is ignored (console warning).
  • Limits: only objects placed straight on a frame switch (one inside a group or inside a mesh object's content is part of that picture); a mesh object switched to a mesh with another number of points loses its pulls (the editor does the same); the object of an object layer only switches picture → picture (its clip / text / video stays what it is); a switched nested clip starts over. hm05-lite does not switch.

Sound ​

Timeline sounds play by themselves (event sounds from their frame, stream sounds while the timeline plays through them). Scripts use the shared sound engine (the browser's Web Audio API underneath — no audio library) or clip.playSound(name, opts). Browsers keep sound off until the page is touched: plays asked for before then start on the first touch / click / key (sound.unlock() from your own gesture handler does it too; sound.audioContext is the page's AudioContext). Every sound is in a group: "effects" (default) or "music". Music plays one at a time — a new music sound stops (or crossfades with) the one playing, and the same music already playing keeps on. A timeline sound's group is set in the editor (Properties → Sound → Group).

ts
import { sound } from "pixi-hm05";
const h = sound.play("boom", { volume: 0.8, loops: 2, effect: "fadeOut" });
sound.playMusic("theme", { crossfade: 2 }); // = play(…, {group: "music", loops: 0})
sound.stopMusic(1);                         // fade out over 1 s
sound.setGroupVolume("music", 0.5);         // on top of each sound's volume
sound.setGroupMuted("effects", true);
sound.pauseAll(); sound.resumeAll();        // or pauseAll("music"); keeps the place
sound.volume = 0.8; sound.muted = false;    // master
sound.musicCrossfade = 1;                   // default fade between music sounds

A SoundHandle has stop(fadeSeconds?), pause() / resume(), seek(t), update(opts), time, playing, paused, group, onEnd.

Marker hit tests ​

Markers (hit boxes, points, polygons … drawn on marker layers) are game data: an export script hands them to the game (api.markers() → MarkerInfo: shape, geometry, matrix, parabola), or keep your own JSON of { shape, geometry }.

On display objects — markers on any children of a common parent:

ts
import { hitTestMarkers } from "pixi-hm05";
const { hit, point } = hitTestMarkers(
	{ marker: bodyBox, object: hero },
	{ marker: attackBox, object: enemy.getChildAt(2) },
	{ space: hero }, // the point in hero's coordinates; default = the root (e.g. the stage)
);

As plain data — e.g. a game's logic world with no pictures (rollback netcode). pixi-hm05/markers is that library alone, without pixi.js:

ts
import { hitTestMarkerData, symbolMarkersAt } from "pixi-hm05/markers";
const [body] = symbolMarkersAt(animFile, "hero", frame, { type: "body" }); // animation.json carries markers as data
hitTestMarkerData(
	{ marker: body.data, x: hero.x, y: hero.y, scaleX: hero.facing },
	{ marker: attackBox, x: enemy.x, y: enemy.y, centerScale: 1.5 }, // grown about its own centre
);

Deterministic: no Math.hypot, circles from a constant table, rotations in steps of 90° exact (other angles use Math.cos / sin; pass a matrix you computed if you need bit-equal results across engines). symbolMarkersAt includes the markers inside the instances a symbol shows (deep, default true), mapped into its space.

Flash-style, on clips (a small game without a separate logic world):

ts
const hit = fighterA.hitTestMarkers(fighterB, { type: "fist", otherType: "body" });
if (hit) spark.position.copyFrom(hit.point); // point in the root's space (or `space`)
fighterA.markerHits(fighterB); // every touching pair
fighterA.markers(); // its markers + those of its child clips, at the frames really shown

Placement x / y / scale / scaleX / scaleY / rotation (or matrix) is the owner's transform; centerScale grows the marker about its centre (a polygon's own centre when set, else its centroid). Boxes (AABB) are checked first. Areas: rect, circle, ellipse, polygon (concave too); paths: arrow / hline / vline / parabola; points. Data tags never hit. point = the centre of the overlap. markerHitShape resolves a marker once for many tests (hitTestShapes).

Collision layers, enter / exit ​

A marker's collision layer is its marker TYPE's name (an "attack box" and a "hurt box" are two types), or whatever layerOf returns. The Layer Collision Matrix belongs to the query, not the file:

ts
const hits = fighterA.markerHits(fighterB, {
	layers: ["attack"], otherLayers: ["hurt"], // which markers take part
	matrix: { attack: ["hurt"] },              // which layers may touch (read both ways)
});

MarkerTracker turns frames of hits into events — one punch is one hit, not ten frames of damage:

ts
import { MarkerTracker, markerPairKey } from "pixi-hm05";
const track = new MarkerTracker(markerPairKey, { onEnter: (h) => hurt(h.point), onExit: (h) => … });
// every frame:
const { entered, stayed, exited } = track.step(fighterA.markerHits(fighterB, { matrix }));

It holds nothing but the last frame's pair keys (save() / restore() roll it back with the game state) and is also in pixi-hm05/markers.

Tweens with the editor's ease curves ​

ts
import { tween, TweenRunner } from "pixi-hm05";
await tween(pickup, { x: 300, alpha: 0 }, { seconds: 0.4, ease: "backOut" });

ease takes a preset name (the editor's: "easeOut", "elasticIn", "bounceOut" …), an ease as the file carries it ({kind: "curve", keys} — a curve a user drew in the Tween Editor) or your own function; keys are property paths ("scale.x"). A tween ticks on Ticker.shared and stops while the player is paused; cancel() / finish() / await it. With clock: null or a TweenRunner you call step(ms) yourself — deterministic, for a game's own fixed-step loop.

Inspecting a running page ​

The hm05 editor's Preview Inspector uses this; your own tools can too. Nothing is made, and nothing runs per frame, until it is called.

ts
import { inspector, play } from "pixi-hm05";
const r = await play();
const ins = inspector(r);
ins.tree();              // [{name, symbol, section, frame, last, playing, inputs?, children}, …]
ins.pause(); ins.step(); ins.resume();   // = playerClock below
ins.showHitBoxes(true);  // draws every marker on stage

playerClock.pause() / resume() / step(ms) hold the whole runtime: everything pixi-hm05 runs ticks on Ticker.shared (clips — also ones your script made — tweens, playSteps, onEnterFrame, videos), and pausing stops that ticker and holds sounds and videos. The app's own ticker keeps drawing; your own app.ticker callbacks keep running.

play() also puts __HM05_INSPECT__({op: "tree" | "pause" | "resume" | "step" | "hitBoxes", …}) on the page (JSON in → JSON out) for a debugger in another window or process.

The format ​

The JSON is @hm05/anim-format v1 (types ship with this package as AnimFile): symbols with layers of keyframe runs, tweens baked to one matrix per frame, sprites as atlas rectangles, labels, scenes and frame commands. Unknown versions are refused by Asset.load.

License ​

MIT

HereSplash — 2D animation for the web