API reference
Use the one-call media API, compact or object frames for custom rendering, and snapshot helpers for still exports. Browser MediaRecorder handles video recording separately.
One-call API
asciify(source, canvas, options?)Returns Promise<() => void>Convert an image (URL string, HTMLImageElement, HTMLVideoElement, or HTMLCanvasElement) and render onto a canvas. Handles loading, conversion, and rendering. Returns a cleanup function; call it on unmount, including for a still image.
asciifyGif(source, canvas, options?)Returns Promise<() => void>Fetch and animate an animated GIF as ASCII art. Source can be a URL string or ArrayBuffer. Returns a stop() function to cancel the animation loop.
asciifyVideo(source, canvas, options?)Returns Promise<() => void>Stream a video as live ASCII art in real time. Defaults to live decoding after the source is ready. Pass preExtract: true for short pre-extracted clips; extraction consumes time and memory. Pass fitTo to auto-size the canvas to a container. Use trim: { start, end } to play only a slice of the video, and scroll to scrub it with the page. Use chromaKey: true to remove green screens. Returns a stop() function.
asciifyWebcam(canvas, options?)Returns Promise<() => void>Ask for camera access and draw the live feed as ASCII. Options: fontSize, options, liveOptions (a function read every frame, so UI controls apply without restarting the camera), mirror (default true), constraints (passed to getUserMedia, default { facingMode: 'user' }) and dpr. Throws when getUserMedia is unsupported or permission is denied. stop() ends the loop and releases the camera.
import { asciifyWebcam } from 'asciify-engine';
// Call from a user gesture, such as a "Start camera" button.
try {
const stop = await asciifyWebcam(canvas, {
fontSize: 8,
mirror: true,
options: { colorMode: 'fullcolor' },
});
// When the view unmounts: stop();
} catch {
// No camera, or permission denied: show a file-upload fallback.
}Live vs pre-extracted
Decodes while playing, after media loading. It does not keep the entire clip as ASCII frames in memory. Useful for looping media and heroes.
const stop = await asciifyVideo(src, canvas);Extracts frames before playback, adding startup time and memory use. The default extraction window is 10 seconds; use an explicit trim range for the clip you need.
await asciifyVideo(src, canvas, { preExtract: true });| Property | Live decoding | Pre-extracted |
|---|---|---|
| Startup | after media loads | after frame extraction |
| Memory | no full ASCII clip cache | grows with cached frames |
| Clip window | source or trim range | 10s default; explicit trim supported |
| Scroll | supports scroll mapping | supports cached-frame scrubbing |
| Best for | loops · hero · webcam | short clips · scrub |
{
fontSize?: number; // character size in px — default: 10
artStyle?: 'classic'; // core uses classic; other styles live in /studio
options?: Partial<AsciiOptions>; // any field from the full AsciiOptions object
// asciifyVideo only:
fitTo?: HTMLElement | string; // fit canvas to container + auto-resize
objectFit?: 'cover' | 'contain' | 'fill' | 'none' | 'scale-down';
objectPosition?: string; // CSS-style placement
fps?: number; // processing cadence
maxRenderDimension?: number; // processing limit; keep within source dimensions
maxCachedFrames?: number; // bounded scroll frame cache
scroll?: boolean | VideoScrollScrubOptions;
preExtract?: boolean; // pre-decode all frames (default: false)
trim?: { start?: number; end?: number }; // play a time slice (seconds)
onReady?: (video) => void; // called once when ready
onFrame?: () => void; // called after every frame
}ASCII background API
background (asciify-engine/kit)(element, { preset, clear?, cursor?, mark?, charset?, palette?, ink?, accent?, cellSize?, speed?, opacity?, dither?, text?, look?, ... })Returns BackgroundHandleDraw an animated ASCII background under an element's content on the GPU glyph field. Import the preset by name (swell, halo, caustics, ...). cursor: false turns the pointer response off. Returns update, setPreset (cross-fades), play, pause, destroy, supported and field. For a page-wide pointer trail, see cursorTrail; for the hero's ground in one call, fieldBackground.
Low-level API
Use these when you need full control — custom render loops, compositing, or embed code generation.
imageToAsciiTextFrame(source, options, targetWidth?, targetHeight?)Returns AsciiTextFrameConvert to compact row strings and optional full-color data. Useful for dense media without per-cell mutation.
renderTextFrameToCanvas(ctx, textFrame, options, width, height)Returns voidDraw a compact frame. Use the same options for conversion and rendering; do not pass an object-cell AsciiFrame here.
import { DEFAULT_OPTIONS, imageToAsciiTextFrame, renderTextFrameToCanvas } from 'asciify-engine';
const options = { ...DEFAULT_OPTIONS, fontSize: 7, colorMode: 'fullcolor' as const };
const frame = imageToAsciiTextFrame(image, options, 720, 405);
renderTextFrameToCanvas(ctx, frame, options, 720, 405);imageToAsciiFrame(source, options, targetWidth?, targetHeight?)Returns { frame: AsciiFrame; cols: number; rows: number }Convert an image, video frame, or canvas to a single AsciiFrame. Reads pixel data including alpha. Returns a 2D cell grid indexed [row][col].
renderFrameToCanvas(ctx, frame, options, canvasWidth, canvasHeight, time?, hoverPos?)Returns voidRender a single AsciiFrame onto a 2D canvas context. Supports ASCII and Dots render modes, animation effects, and interactive hover. Performance depends on cell count, effects, and target hardware.
gifToAsciiFrames(buffer, options, targetWidth, targetHeight, onProgress?)Returns Promise<{ frames, cols, rows, fps }>Parse an animated GIF (ArrayBuffer) and convert every frame to ASCII. Handles GIF disposal methods, compositing, and frame timing.
videoToAsciiFrames(video, options, targetWidth, targetHeight, targetFps?, maxDuration?, onProgress?)Returns Promise<{ frames, cols, rows, fps }>Seek through a video element at the given FPS rate and convert each frame to ASCII. maxDuration limits extraction (default: 10s).
Snapshot API
Capture a single frame from a live ASCII canvas as a PNG, JPEG, or WebP.
captureSnapshot(canvas, options?)Returns Promise<Blob>Capture a single frame from a canvas as a Blob. Supports png, jpeg, and webp formats with optional quality and scale.
snapshotAndDownload(canvas, options?)Returns Promise<void>Capture a single frame and immediately trigger a browser download. Combines captureSnapshot with a temporary object URL.
import { captureSnapshot, snapshotAndDownload } from 'asciify-engine';
// Get a Blob you can upload or preview
const blob = await captureSnapshot(canvas, { format: 'png' });
const url = URL.createObjectURL(blob);
// When the preview is removed: URL.revokeObjectURL(url);
// Or trigger a download directly
await snapshotAndDownload(canvas, { format: 'jpeg', filename: 'my-art' });Data types
interface AsciiCell {
char: string; // Character mapped from luminance
r: number; // Red component (0–255)
g: number; // Green component (0–255)
b: number; // Blue component (0–255)
a: number; // Alpha channel (0–255)
}
type AsciiFrame = AsciiCell[][]; // 2D grid [row][col]
interface AsciiResult {
frames: AsciiFrame[];
cols: number;
rows: number;
fps: number;
}Cleanup and caches
Every one-call API resolves to a cleanup function, including asciify() for a still image. A component can unmount before that promise resolves, so keep a flag and call the cleanup as soon as it arrives.
let disposed = false;
let stop: (() => void) | undefined;
asciifyVideo(src, canvas, { fitTo: host }).then(cleanup => {
if (disposed) cleanup(); // unmounted while loading
else stop = cleanup;
});
// On unmount:
disposed = true;
stop?.();AsciiFrame is immutable to the renderer: with hover on, renderFrameToCanvas caches a still frame's drawing by object identity and redraws only the cells near the cursor. After editing cells, pass a new frame instead of mutating the old one.
// Replace, don't mutate: a new array invalidates the cached drawing.
frame = frame.map(row => row.map(cell => ({ ...cell, char: cell.char === '@' ? '#' : cell.char })));
renderFrameToCanvas(ctx, frame, options, width, height);clearAsciifyCaches()Returns voidClear the shared renderer caches: charset lookups, cached still drawings, hover state and the sampling canvas. Call it in long-lived editors that cycle through many fonts and charsets.