@kartore/spritore
v0.4.0
Published
Generate MapLibre sprite sheets from SVG icons in browsers, Node, and the command line
Readme
@kartore/spritore
@kartore/spritore turns SVG icons into the PNG sprite sheet and JSON index
used by MapLibre GL styles. It can also rasterize one
SVG into RGBA pixels for map.addImage previews.
The package can be used as a command, in a browser, or in Node. Typical uses include generating style assets during a build, adding live icon previews to a map editor, and letting users download a completed sprite from a web app.
Install
pnpm add @kartore/spritoreOr with npm:
npm install @kartore/spritoreCLI
The package includes a spritore executable. It reads lowercase .svg files
from a directory and writes MapLibre PNG and JSON sprite assets:
npx @kartore/spritore build ./icons -o ./public/spritesBy default it generates:
public/sprites/
├── sprite.png
├── sprite.json
├── [email protected]
└── [email protected]Available options:
spritore build <svg-dir> -o <out-dir> [--name sprite] [--ratio 1,2] [--fast] [--sdf] [--skip-invalid]--name <name>changes the output basename.--ratio <ratios>accepts comma-separated integers from 1 to 255.--fastprioritizes generation speed over PNG file size.--sdfrenders every icon as a MapLibre SDF icon (see SDF icons).--skip-invalidreports SVG parse errors and continues with valid icons.
Without --skip-invalid, an invalid SVG stops the command before output files
are written. Icon IDs come from filename stems; characters outside
a-zA-Z0-9_- become -, and collisions after conversion are errors.
Browser
The rendering functions initialize the bundled WebAssembly module automatically on their first call:
import {
buildSpriteSheet,
renderIcon,
} from "@kartore/spritore";
const markerSvg = `
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16">
<circle cx="8" cy="8" r="6" fill="#4264fb" />
</svg>
`;
const marker = await renderIcon("marker", markerSvg, 2);
map.addImage("marker", {
width: marker.width,
height: marker.height,
data: marker.pixels,
});
const sprite = await buildSpriteSheet(
[{ id: "marker", svg: markerSvg }],
2,
);Initialization is cached across both functions. Advanced integrations can use
the wasm option on the first call to provide custom WebAssembly bytes or a
URL; normal browser usage does not need this option.
Node
Use the /node entry point so the packaged WebAssembly file is loaded from the
filesystem:
import { readFile, writeFile } from "node:fs/promises";
import { buildSpriteSheet } from "@kartore/spritore/node";
const markerSvg = await readFile("marker.svg", "utf8");
const sprite = await buildSpriteSheet(
[{ id: "marker", svg: markerSvg }],
1,
);
await writeFile("sprite.png", sprite.png);
await writeFile("sprite.json", sprite.indexJson);Write indexJson directly when creating a sprite index. The index property
contains the parsed object for applications that need to inspect or transform
entries. Result objects, the index, and each index entry are frozen plain
objects. The Uint8Array values are caller-owned and require no manual
cleanup.
API
renderIcon(id, svg, pixelRatio, options?)
Rasterizes one SVG and asynchronously returns straight-alpha RGBA pixels:
type RenderedIcon = {
readonly id: string;
readonly width: number;
readonly height: number;
readonly pixels: Uint8Array;
/** true when pixels hold a signed distance field */
readonly sdf: boolean;
};
type RenderIconOptions = {
/** Render a MapLibre SDF icon. Defaults to false. */
readonly sdf?: boolean;
readonly wasm?: string | URL | ArrayBuffer | Uint8Array |
Promise<string | URL | ArrayBuffer | Uint8Array>;
};Use the returned width, height, and pixels as MapLibre's
map.addImage image data, and pass sdf through to its options
(map.addImage(id, icon, { pixelRatio, sdf: icon.sdf })). A pixel ratio of
1 or 2 covers typical standard- and high-density previews.
buildSpriteSheet(icons, pixelRatio, options?)
Rasterizes a collection of SVG icons and asynchronously returns complete MapLibre sprite assets:
type SpriteSheet = {
readonly png: Uint8Array;
readonly index: Readonly<Record<string, {
readonly x: number;
readonly y: number;
readonly width: number;
readonly height: number;
readonly pixelRatio: number;
/** present only for SDF icons */
readonly sdf?: true;
}>>;
readonly indexJson: string;
};
type BuildOptions = {
readonly fast?: boolean;
readonly wasm?: string | URL | ArrayBuffer | Uint8Array |
Promise<string | URL | ArrayBuffer | Uint8Array>;
};Each input item has an id used as its index key, an svg string, and an
optional sdf flag. Duplicate IDs, empty icon arrays, invalid SVG, and zero-sized icons are errors.
SDF icons
MapLibre can tint single-colour icons with icon-color and draw
icon-halo-* around them when the sprite marks them as SDF (signed distance
field) icons. spritore renders an icon as an SDF when asked:
- the image keeps only the icon's alpha (RGB is zero), so original colours are lost;
- 3 logical pixels of transparent padding are added on every side (6 pixels at
pixel ratio 2), so halos up to 3 pixels wide fit. The padding makes the image
larger, so anchors such as
icon-anchor: bottommove by that amount; - distances use a radius of 8 logical pixels and a cutoff of 0.25, matching MapLibre's SDF shader;
- the sprite index entry gets
"sdf": true.
Stretchable icons (9-slice)
For icon-text-fit, MapLibre reads per-icon stretchX, stretchY,
content, textFitWidth, and textFitHeight from the sprite index. Pass
them with an icon in logical pixels of the SVG; spritore writes them in
image pixels for each pixel ratio (and shifted by the padding for SDF icons):
await buildSpriteSheet(
[
{
id: "label-box",
svg,
stretchX: [[4, 20]],
stretchY: [[4, 12]],
content: [4, 4, 20, 12],
textFitWidth: "stretchOrShrink",
},
],
2,
);
// [email protected]: "stretchX": [[8, 40]], "stretchY": [[8, 24]], "content": [8, 8, 40, 24], …
const box = await renderIcon("label-box", svg, 2, { stretchX: [[4, 20]] });
map.addImage("label-box", box, { pixelRatio: 2, stretchX: box.stretchX });Values must stay inside the image, and stretch ranges must be ascending and
non-overlapping (MapLibre's rules); otherwise rendering fails. textFitWidth
and textFitHeight accept stretchOrShrink, stretchOnly, or
proportional. The CLI does not set per-icon metadata.
Build modes
The default mode prioritizes smaller PNG files and is intended for final
assets. Pass { fast: true } when quicker generation matters more than file
size, such as during interactive previews:
const preview = await buildSpriteSheet(icons, 2, { fast: true });SVG limitations
- External resources such as linked images and web fonts are not loaded.
- SVG
<text>is not supported because fonts are not bundled. Text elements may parse successfully but are not rendered.
Development
Install the repository's pinned Rust toolchain, the wasm target, the matching
wasm-bindgen CLI, Binaryen's wasm-opt, Node, and pnpm:
rustup target add wasm32-unknown-unknown
cargo install wasm-bindgen-cli --version 0.2.125 --locked
pnpm install
pnpm build
pnpm typecheck
pnpm test
pnpm bench
pnpm --filter @kartore/spritore pack --dry-runThe build stops if wasm-bindgen has a different version or wasm-opt is not
available. Generated files under js/pkg/ and js/dist/ are built before
testing and publishing.
License
Licensed under either the Apache License, Version 2.0 or the MIT License, at your option.
