Skip to content

Export scripts: your own format in JavaScript ​

File › Export › Export with Script… runs a .js file you wrote. The script gets a read-only copy of the document and an API to list every object of a frame, measure it, read its position / rotation / scale / skew, opacity, filters, blend mode and children, draw a frame or a single object into a canvas (which you can keep drawing on with Canvas 2D), pack sprite sheets, and finally write any files: PNG, JSON, text, binary.

Scripts run in a sandbox (a Web Worker): they cannot change the document and have no network unless you allow it. A script with a mistake or an endless loop can be stopped with Cancel; the editor never hangs. Example scripts and a type file (VS Code autocompletion) come with it.

The full API is in the export / import script reference.

Getting started ​

  1. File › Export › Export with Script….
  2. Press Examples to add the example scripts, or Add Script… (Add / Reload… once a script is chosen) to pick your own .js files (several at once is fine). Adding a file with the same name again replaces that script: that is how you reload a script after changing it. Script Kit downloads hm05-script-kit.zip: the type file, a README, a jsconfig.json and the examples.
  3. Set the fields at the top as usual (File name, Timeline, Scenes, Frames, Scale, Layers, Transparent background); the script's own options appear below them. Press Export. One file written = that file is downloaded; more than one = <File name>.zip.

Try it: in a new document draw a square, convert it to a symbol, give the instance the name hit_box, add a few frames to the timeline, then File › Export › Export with Script… › Examples › choose "Example: named object boxes (hitboxes)" › Export. The ZIP holds a debug picture per frame (the square with a pink box drawn around it) and <File name>-boxes.json (the four corners of each box, in picture pixels).

  • Added scripts are kept in this browser / app ("my scripts", available in every project); they are not saved in the .hm5 file. Each script's option values are remembered too.
  • api.log() / console.log() output and errors (with line numbers) show at the bottom of the dialog.
  • Automation: hm05.run("export.addScript", code, "name.js"), export.addExampleScripts, export.removeScript, export.downloadScriptKit, then hm05.run("exportScript.run", { scriptId }) (see Automation).

What a script looks like ​

js
/// <reference path="./hm05-script.d.ts" />
// @ts-check
export default hm05.defineExporter({
	name: "My format", // shown in the Script list
	description: "One PNG per frame + object positions",
	options: [{ key: "big", label: "Twice the size", type: "boolean", default: false }],
	async run(api, options) {
		const data = [];
		for (const f of api.frames()) {
			// every frame chosen in the dialog
			api.progress(f.index, api.frames().length);
			const shot = await api.render.frame({ frame: f.frame, scale: options.big ? 2 : undefined });
			await api.output.write(`frames/${f.index}.png`, shot);
			data.push(api.objects({ frame: f.frame }).map((o) => ({ name: o.name, ...o.transform })));
		}
		await api.output.json("data.json", data);
	},
});
  • One .js file = one ES module that does export default hm05.defineExporter({...}). run may be async; throw new Error("…") stops the export and shows the message.
  • Put hm05-script.d.ts next to the script and keep the /// <reference …> first line: VS Code then completes the whole API with its descriptions (every field is commented). The type file is the API's definitive description.
  • To have an AI write a script for you, give it hm05-script.d.ts and one example, and describe the format you want.

Options ​

typeShown asOther fields
numbernumber fielddefault, min, max, step, integer
booleancheck boxdefault
stringtext fielddefault
selectdrop-down listchoices: ["a", "b"] or [{ value, label }]
symbolLibrary symbol list (value = symbol id, "" = the main timeline)
colorcolour (value = "#rrggbb")default

Every field needs a key; label is the text shown (default: the key), title the tooltip. A value that is not allowed (out of range, not in the list) is replaced by the default.

Reading the document ​

Coordinates and units (read this first) ​

  • Frames count from 0 (frame 1 on the timeline = frame: 0). Without a scene, frames run across all scenes (played one after the other).
  • "Timeline coordinates" = the coordinates of the timeline you query: the main timeline = stage coordinates; a symbol = the symbol's own (origin = its registration point). Queries look at the dialog's Timeline unless told otherwise.
  • Angles are degrees, clockwise (y points down, as on the stage). A negative scale = flipped.
  • Positions and sizes are document units (stage pixels at 100%); pictures from api.render are output pixels = units × scale. To convert: pixel = (point − shot.region.x) × shot.scale (the same for y).
  • A matrix [a, b, c, d, tx, ty] maps a point (x, y) to (a·x + c·y + tx, b·x + d·y + ty), the same as canvas setTransform(a, b, c, d, tx, ty).

Queries ​

FunctionReturns
api.frames()the frames chosen in the dialog (Timeline / Scenes / Frames): index (output number), frame, scene, sceneFrame, label
api.timeline({ symbol })frame count, fps, scenes (start / length), labels, layers (with folder path, mask, guide, exported or not)
api.symbols() / api.symbol(nameOrId)Library symbols: id, name, folder, frame count, scenes, export id, stopAtEnd
api.layers({ frame })the layers at a frame: alpha, shown or not, blend mode, filters, movement from layer tweens / canned motions (matrix / transform), current keyframe, bounds
api.objects({ frame, layer, deep, layers })every object at a frame (tweens, motion guides and layer movement applied), bottom to top (drawing order). deep: false = no children
api.find(nameOrId, { frame })the first object at any depth whose instance name / id / key matches; none = null
api.flatten(objects)the object tree as one list (parents before children)
api.bounds({ frame })that frame's picture bounds (timeline coordinates, filters included)
api.exportBounds()the bounds of every exported frame together (render.frame uses them by default, so every frame lines up)
api.markerTypes() / api.markers({ frame, type, layer, deep })marker types and the markers at a frame

Every query also takes symbol (a symbol name or id; null = the main timeline), scene (name or id) and layers: "export" (default: the layers chosen in the dialog's Layers; inside a symbol, the visible layers), "all" (every layer that draws, masks included) or a list of layer names / ids.

Objects (ObjectInfo) ​

FieldMeaning
id, key, typeobject id; unique path "layerId/objectId[/child…]"; kind: shape, line (lines only), group, mesh, bitmap, text, footage, symbol, picture (a picture of a bitmap layer)
nameinstance name (symbol instances, texts; the name of an object layer is read too)
layer, depth, parent, zits layer; 0 = on the timeline, 1 = inside a group / symbol …; the parent's key; order within the layer (0 = bottom)
symbolsymbol instances: symbol id, name, the frame of the symbol shown now, frame count, loop mode
transformon the timeline: x, y (registration point), rotation (degrees), scaleX / scaleY, skew, with every parent applied
localTransformrelative to the parent (= the numbers the Properties / Transform panels show)
matrix / localMatrixthe same as matrices
localBoundsthe object's own size (untransformed)
boundsaxis-aligned box on the timeline
drawnBoundsbounds + what filters draw outside it (shadows, glows)
corners, centerthe four corners after rotation (top-left, top-right, bottom-right, bottom-left) and the centre: use these for hit boxes
opacity, alphaits own opacity; the opacity it is shown with (own × parents × layer)
blendModeblend mode (its layer's; inside a symbol the nearest one that is not normal)
filters, layerFiltersthe instance's own filters (type + parameters + on / off); its layer's filters
colorEffectcolour effect (brightness / tint / advanced)
fill, stroke, text, imageshape colours, lines, text contents, picture (asset id / picture id / size)
childrena group's objects; for a symbol instance the objects of the symbol's frame shown (same shape, also in timeline coordinates)
elementthe raw document data (read-only)

Drawing (canvas) ​

api.render ​

FunctionDoes
render.frame({ frame, scale, region, padding, background, layers })draws a frame. region: "export" (default; the same box for every frame, so they line up), "content" (this frame's picture), "stage" or {x, y, width, height}
render.object(object, { space, scale, padding })draws one object. space: "local" (default) = as it is, not rotated or scaled (for sprites placed back with matrix); "timeline" = as on screen (rotated, scaled)
render.asset(assetId)a picture imported into the Library (original size)
render.picture(imageId)a picture of a bitmap layer (all its sub-layers together)

Each returns a ScriptImage: canvas (an OffscreenCanvas you can draw on with Canvas 2D), width, height, region (what was captured, in units), scale, origin (where the coordinate origin / registration point is in the picture, in pixels = the sprite's pivot).

js
const shot = await api.render.frame({ frame: 0 });
const g = shot.canvas.getContext("2d");
g.strokeStyle = "#ff0000";
g.strokeRect(10, 10, 50, 50); // draw on the exported picture
await api.output.write("debug.png", shot);

api.image (picture tools) ​

FunctionDoes
image.create(w, h)a new transparent canvas
image.trim(picture, { alpha, padding })crops transparent edges; returns x / y (where it was in the original); a ScriptImage's origin / region are corrected
image.pack(pictures, { layout, padding, columns, powerOfTwo })one sprite sheet: "packed" (smallest), "grid" (equal cells), "row", "column"; returns the canvas and each picture's rects (in input order)
image.resize(picture, w, h, { smooth })scales
image.toBlob(picture, type, quality)encodes PNG (default) / JPEG / WebP
image.pixels(picture)the RGBA pixels (ImageData)

There is also api.math: multiply, invert, apply (a point), decompose (matrix → x / y / degrees / scale / skew), compose, transformBounds, unionBounds.

Writing files ​

FunctionDoes
output.write(path, data)data can be a string, Blob, ArrayBuffer, Uint8Array, a canvas or a ScriptImage (→ PNG). The path may have folders ("sprites/a.png"); writing the same path again replaces it
output.json(path, value, indent)JSON (indent 2 by default, 0 = one line)
output.list()the paths written so far
api.progress(done, total)progress on the Export button
api.log(...)the log at the bottom of the dialog

The web editor and the desktop app both download: one file as it is, several as a ZIP. A script that writes nothing counts as an error.

The examples ​

ExampleShows
sprite-sheet.jsevery frame captured in the same box → trimmed → packed into one PNG; JSON with each frame's position, pivot (where the registration point is after trimming), label animations, fps. Options: trim, layout, spacing, power of two
cutout-data.js"cut-out animation": each symbol drawn once (as it is) into an atlas; JSON with each instance's x, y, rotation, scale, skew, alpha, blend mode, filters and symbol frame for every frame, children optional. A game engine places the pieces itself from these numbers
hitboxes.jsfinds objects whose instance name starts with a prefix (e.g. hit_), writes their four rotated corners (in picture pixels), and draws the boxes and names on each frame's picture with Canvas 2D as a debug picture
markers.jseach frame's markers (hit boxes, spawn points, directions …) with their field values, in timeline units, markers inside symbol instances included; one JSON file
lf2r-export.jswrites a symbol back to Little Fighter 2 Remastered data + PNGs (the reverse of the import example below)

Import scripts ​

The same kind of script can import: hm05.defineImporter({ name, accept, options, run(api, options) }), used from File › Import › Import with Script…. The script reads the file you picked (api.input) and files next to it (api.files.read("../pics/a.png"); the desktop app asks once before reading outside that folder, the web editor asks you to pick the folder), then builds content with api.build.markerType (skipped when one of that name exists), api.build.image (can be cut into a sprite sheet) and api.build.symbol (layers, keyframes, picture / symbol objects, markers, labels). Everything is added in one go when the script ends: one undo step. The example "Little Fighter 2 Remastered data" turns the game's data files and sprite sheets into a symbol. The types are ImportApi in hm05-script.d.ts.

Allow internet access: every script (export and import) has this check box, off by default. While it is off the worker has no fetch / XHR / WebSocket; turn it on only for scripts you trust. In the desktop app a script added from a file remembers where the file is and reads it again before each run.

Safety and limits ​

  • Read-only: the script gets a frozen copy of the document; a write such as api.document.name = "x" throws a TypeError. The document in the editor is not affected and nothing is added to the undo history.
  • No network (unless allowed): fetch, XMLHttpRequest, WebSocket and the like are removed; IndexedDB and caches cannot be read either.
  • Scripts run in a Web Worker: an endless loop does not freeze the editor, and Cancel ends the script at once. Pictures are drawn by the editor (the same renderer as every other export) and handed to the script.
  • The export uses the document as it is when you press Export.
  • api.frames() are the frames chosen in the dialog, once each and in order; Playback actions (stop / goto / wait …) are not run. Read the actions from api.document yourself when you need them.
  • Scripts are kept in the browser's localStorage (about 5 MB at most; a script is usually a few KB).

HereSplash — 2D animation for the web