Documentation / @ripl/core
@ripl/core ​
The rendering core of Ripl: elements, scene graph, renderer, animation, scales, colour and math, drawing through a
Contextabstraction that Canvas, SVG, the terminal and WebGPU each implement.
Features ​
- Ten built-in elements — arc, circle, ellipse, image, line, path, polygon, polyline, rect and text, each with a
createXfactory, anelementIsXtype guard and full stroke/fill state. Polylines carry thirteen curve algorithms (linear, spline, basis, bump-x, bump-y, cardinal, catmull-rom, monotone-x, monotone-y, natural, step, step-before, step-after). - DOM-like scene graph — elements nest in groups that inherit presentation state, and are found with
getElementById,getElementsByType,getElementsByClass,query,queryAll,matchesandclosest.Scenehoists the tree into a flat render buffer, so a frame costs O(n) in elements rather than in tree depth. - Renderer —
createRendererdrivesrequestAnimationFrame, stops itself when nothing is animating (autoStop), and carries FPS, element-count and bounding-box debug overlays. - Animation — awaitable, cancelable transitions with CSS-like keyframes, per-keyframe offsets, and 31 easing functions (linear plus quad, cubic, quart, quint, sine, expo, circ, back, elastic and bounce in in/out/in-out form). See Animations.
- Type-aware interpolation — every built-in element declares how its own state tweens, so a colour, gradient, pattern fill, rotation, point set or dash pattern animates without configuration; anything undeclared is detected from the value. The
interpolatorsoption overrides any property, on a custom element or a built-in one. Point-set morphing matches outlines of differing length by key, so a curve stays curved across the transition. - Events — a typed
EventBuswith bubbling, delegation,stopPropagation,{ self: true }filtering and disposable subscriptions, plus pixel-accurate hit testing so a pointer event resolves to the element actually drawn under the cursor. - 14 scale types — continuous, band, point, discrete, ordinal, diverging, logarithmic, power, symlog, quantile, quantize, threshold, radial and time. See Scales.
- Colour — parsing and serialisation for hex,
rgb()/rgba(),hsl()/hsla(),hsv()/hsva()and the 148 CSS colour keywords, conversion between spaces, alpha manipulation, sequential colour scales and 8 built-in schemes (viridis, plasma, inferno, magma, cividis, turbo, RdBu, BrBG). - Gradients and patterns — linear, radial and conic gradients (including repeating variants) parsed from CSS gradient strings, and five pattern tiles (diagonal, cross-hatch, dots, horizontal, vertical). Both are ordinary paint strings, so they inherit and interpolate like any other style.
- Math — points, angles, distances, bounding boxes, matrices and polar conversion, plus a
Navigatorthat pans, zooms and brushes by rescaling scale domains rather than scaling geometry, keeping strokes and text crisp. - Strict TypeScript, tree-shakable, no third-party runtime dependencies — the only dependency is
@ripl/utilities, a sibling in this repository.
Installation ​
Browser projects should install @ripl/web instead — it re-exports every symbol below alongside the Canvas 2D context, and registers the browser platform bindings that @ripl/core needs to measure text and schedule frames.
bash
# npm
npm install @ripl/core
# yarn
yarn add @ripl/core
# pnpm
pnpm add @ripl/coreQuick start ​
typescript
import {
createCircle,
createContext,
createRenderer,
createScene,
easeOutCubic,
} from '@ripl/web';
const context = createContext('.mount-element');
const circle = createCircle({
fill: 'rgb(30, 105, 120)',
cx: context.width / 2,
cy: context.height / 2,
radius: 50,
});
const scene = createScene(context, {
children: [circle],
});
const renderer = createRenderer(scene, {
autoStart: true,
autoStop: true,
});
await renderer.transition(circle, {
duration: 1000,
ease: easeOutCubic,
state: {
radius: 100,
fill: '#ff0000',
},
});To render the same scene as SVG, import createContext from @ripl/svg. Nothing else changes.
Key API ​
| Export | What it does |
|---|---|
Context | The rendering abstraction every backend implements |
Element / Shape | Base classes for renderable state, transforms and hit testing |
createGroup | Container with inheritance, querying and event bubbling |
createScene | Top-level group bound to a context, with a hoisted render buffer |
createRenderer | Animation loop and transition manager |
scaleContinuous … scaleTime | The 14 scale constructors |
interpolateColor / ElementInterpolators | Built-in interpolators and the per-property override map |
parseGradient / parsePattern | Paint-string parsing for gradients and pattern tiles |
Navigator | Pan, zoom and brush over a viewport by rescaling domains |
Related packages ​
@ripl/web— the browser entry point, and what most projects should install@ripl/canvas/@ripl/svg/@ripl/terminal— the rendering contexts@ripl/charts— 25 pre-built chart types on top of this package@ripl/3d— 3D shapes, camera, lighting and materials@ripl/devtools— live scene-graph inspection in the browser devtools
Documentation ​
Guides, live demos and the full API reference are at ripl.run/docs/core.
License ​
Namespaces ​
| Namespace | Description |
|---|---|
| interpolateAny | Fallback interpolator factory that snaps from the first value to the second at the halfway point. |
| interpolateBorderRadius | Interpolator factory that transitions between two border-radius values (single number or four-corner tuple). |
| interpolateColor | Interpolator factory that smoothly transitions between two CSS color strings by interpolating their RGBA channels. |
| interpolateDate | Interpolator factory that interpolates between two Date instances by lerping their timestamps. |
| interpolateGradient | Interpolator factory that transitions between two CSS gradient strings by interpolating their stops, angles, and positions. |
| interpolateNumber | Interpolator factory that linearly interpolates between two numbers. |
| interpolateNumbers | Interpolator factory that transitions between two numeric arrays element-wise. |
| interpolatePattern | Interpolator factory that transitions between two pattern(...) paint strings sharing a tile type by interpolating their foreground/background colors and tile size. |
| interpolatePoints | Interpolator factory that transitions between two point arrays. By default it extrapolates additional points where set lengths differ; pass resolveKeys to match points by identity instead (preserving curved renderers across add/remove). |
| interpolateRotation | Interpolator factory that transitions between two rotation values (numbers in radians or strings like "90deg"). |
| interpolateTransformOrigin | Interpolator factory that transitions between two transform-origin values (numbers or percentage strings). |
Classes ​
| Class | Description |
|---|---|
| Arc | An arc or annular sector shape supporting inner radius, angular or constant-width padding, and rounded corners. |
| Box | An axis-aligned bounding box defined by its four edges. |
| Circle | A circle shape rendered at a center point with a given radius. |
| ColorParseError | Error thrown when a color string cannot be parsed in the expected format. |
| Context | Abstract rendering context providing a unified API for Canvas and SVG, with state management and coordinate scaling. |
| ContextPath | A virtual path element used to record drawing commands; subclassed by Canvas and SVG implementations. |
| ContextText | A virtual text element capturing position, content, and optional path-based text layout. |
| Disposer | Abstract base class that manages disposable resources, supporting keyed retention and bulk disposal. |
| Element | The base renderable element with state management, event handling, interpolation, transform support, and context rendering. |
| Ellipse | An ellipse shape rendered at a center point with separate x/y radii, rotation, and angle range. |
| Event | An event object carrying type, data, target reference, and propagation control. |
| EventBus | A typed pub/sub event system with parent-chain bubbling, disposable subscriptions, and self-filtering. |
| Group | A container element that manages child elements, providing scenegraph traversal, CSS-like querying, and composite bounding boxes. |
| ImageElement | An image element that draws a CanvasImageSource at a given position and optional size. |
| Line | A straight line segment between two points. |
| Navigator | An interactive 2D pan/zoom/brush controller, the flat-scene analogue of the 3D Camera. This base class is deliberately context-agnostic: it owns the view model (a { k, x, y } transform plus an optional brush selection) and the imperative commands that mutate it, but it attaches no input listeners of its own. That mirrors the Context/DOMContext split; the DOM-bound DOMNavigator in @ripl/dom extends this class to translate real wheel/pointer/touch gestures into these commands, while non-DOM environments can drive the same view model programmatically (or subclass it with their own input source). |
| Path | A general-purpose shape rendered by a user-supplied path renderer callback. |
| Polygon | A regular polygon shape with a configurable number of sides. |
| Polyline | A multi-point line shape supporting various curve interpolation algorithms. |
| Rect | A rectangle shape with optional rounded corners via border radius. |
| Renderer | Drives the animation loop via requestAnimationFrame, managing per-element transitions and rendering the scene each frame. |
| Scene | The top-level group bound to a rendering context, maintaining a hoisted flat instruction stream for O(n) rendering. |
| Shape | Abstract base class for renderable shapes, extending Element with a type-constrained constructor. |
| Shape2D | A concrete 2D shape with path management, automatic fill/stroke rendering, clipping support, and path-based hit testing. |
| Task | A cancelable promise with AbortController integration, supporting abort callbacks and chaining. |
| TaskAbortError | Error thrown when a task is aborted, carrying the abort reason. |
| Text | A text element that renders string or numeric content, with optional path-based text layout. |
| Transition | A Task-based animation that drives a callback over time with easing, looping, and abort support. |
Interfaces ​
| Interface | Description |
|---|---|
| ArcState | State interface for an arc element, defining center, angles, radii, padding, and border radius. |
| BandScale | A band scale that divides a continuous range into uniform bands for categorical data, exposing bandwidth and step. |
| BaseState | The full set of visual state properties inherited by every renderable element. |
| CircleState | State interface for a circle element, defining center coordinates and radius. |
| ColorParser | A color parser that can test, parse, and serialize a specific color format. |
| ColorScale | A callable color scale mapping a numeric value to a CSS color, with domain and tick access. |
| ConicGradient | A parsed conic gradient with angle, position, color stops, and optional repeating flag. |
| ContextElement | Minimal interface for context-level elements (paths, text) identified by a unique id. |
| ContextEventMap | Event map for a rendering context, including resize and pointer events. |
| ContextExport | Snapshot exporter returned by Context.export. Each method serializes the snapshot that was captured at the moment export() was called, so later mutations to the context do not affect the exported result. Contexts implement the formats relevant to them (see each context's export() for specifics); unsupported formats throw a descriptive error. |
| ContextOptions | Options for constructing a rendering context. |
| DivergingScaleOptions | Options for a diverging scale, adding a midpoint to the base linear scale options. |
| ElementEventMap | Event map for elements, extending the base event map with lifecycle and interaction events. |
| ElementValidationResult | The result of validating an element, with a severity type and descriptive message. |
| EllipseState | State interface for an ellipse element, defining center, radii, rotation, and angle range. |
| FactoryOptions | Platform-specific function implementations injected at runtime. |
| FrameBuffer | A debounced requestAnimationFrame scheduler. Calling it schedules a callback for the next frame, replacing any frame already pending, so a burst of calls within one frame collapses into a single callback. |
| GradientColorStop | A single color stop within a gradient, consisting of a CSS color and an optional offset position. |
| GroupOptions | Options for constructing a group, extending element options with an optional initial set of children. |
| ImageState | State interface for an image element, defining position, optional size, and image source. |
| InterpolatePointsFactory | The interpolatePoints factory: a point-array interpolator factory that also accepts InterpolatePointsOptions. |
| InterpolatePointsOptions | Options controlling how interpolatePoints reconciles two point sets. |
| LinearGradient | A parsed linear gradient with angle, color stops, and optional repeating flag. |
| LinearScaleOptions | Options shared by linear-based scales (continuous, logarithmic, power, etc.). |
| LineState | State interface for a line element, defining start and end coordinates. |
| LogarithmicScaleOptions | Options for a logarithmic scale, adding a configurable base to the base linear scale options. |
| NavigatorBrush | A rectangular brush selection in the navigator's pixel space. |
| NavigatorEventMap | Events emitted by a Navigator. |
| NavigatorFitOptions | Options for Navigator.fitBounds. |
| NavigatorInteractions | Configures which navigator interactions (zoom, pan, brush) are enabled. |
| NavigatorOptions | Options for constructing a Navigator. |
| NavigatorTransform | A 2D affine view transform: uniform scale k plus translation [x, y], in logical pixels. |
| NavigatorViewport | The pixel dimensions of the surface the navigator drives (used to center/fit content). |
| OrdinalScale | A callable ordinal scale mapping discrete domain values to a cycling range of output values. |
| PathState | State interface for a path element, defining bounding position and dimensions. |
| Pattern | A parsed repeating pattern (decal) fill, used to keep series distinguishable without relying on color alone. |
| PatternTileDot | A filled circular dot within a pattern tile, filled with the pattern's foreground color. |
| PatternTileGeometry | The renderer-agnostic geometry of a single repeating pattern tile. |
| PatternTileLine | A straight line segment within a pattern tile, stroked with the pattern's foreground color. |
| PointScale | A point scale that positions discrete domain values at evenly spaced points, exposing the step. |
| PointScaleOptions | Options for a point scale, controlling outer padding and alignment within the range. |
| PolygonState | State interface for a regular polygon element, defining center, radius, and number of sides. |
| PolylineSegment | A span of a polyline's points stroked with its own dash pattern. |
| PolylineState | Base state interface for all elements. All visual properties are optional at the element level. |
| PowerScaleOptions | Options for a power scale, adding a configurable exponent to the base linear scale options. |
| Queryable | The structural contract the CSS-like query engine operates on, implemented by every Element. Container elements (Group) additionally provide children and a flattened descendant graph so combinators can traverse the scene tree. Typing the engine against this interface (rather than the concrete classes) lets Element, Group, and the engine live in separate modules without import cycles. |
| RadialGradient | A parsed radial gradient with shape, position, color stops, and optional repeating flag. |
| RadialScaleOptions | Options for a radial scale that maps a numeric magnitude onto a ring radius. |
| RectState | State interface for a rectangle element, defining position, dimensions, and optional border radius. |
| RenderElement | Minimal interface for any element that can be rendered and hit-tested by a context. |
| RenderElementIntersectionOptions | Options for render element intersection testing. |
| RendererDebugOptions | Options for enabling debug overlays on the renderer. |
| RendererEventMap | Event map for the renderer, with start, stop, and per-frame tick events. |
| RendererOptions | Configuration for the renderer, controlling auto-start/stop behavior and debug overlays. |
| RendererTransition | Internal representation of an active transition managed by the renderer. |
| RendererTransitionOptions | Options for scheduling a transition on one or more elements via the renderer. |
| RenderInstruction | A single entry in a Scene's flat render instruction stream. push/pop bracket a group so its transform and any group-scoped clip apply to the leaves drawn between them; draw renders a leaf element. Groups are contiguous (stacking-context ordering), so each group contributes exactly one push/pop pair. |
| ResolvedInteraction | An interaction option resolved to concrete values. |
| Scale | A callable scale with domain, range, inverse mapping, tick generation, and inclusion testing. |
| ScaleBindingOptions | Low-level options for constructing a scale, providing conversion, inversion, inclusion, and tick generation callbacks. |
| SceneOptions | Options for constructing a scene, extending group options with an optional auto-render-on-resize flag. |
| StringInterpolatorTag | A tagged template result capturing the static fragments and dynamic numeric arguments. |
| SymlogScaleOptions | Options for a symmetric-log scale, adding a configurable linear threshold to the base linear scale options. |
| TextState | State interface for a text element, defining position, content, and optional path-based text layout. |
| TransformTarget | The subset of Context transform operations required to apply an element's transform. Implemented by every Context, and by the internal matrix accumulator used to reconstruct an element's world transform for hit testing. |
| TransitionOptions | Configuration for a transition animation. |
Type Aliases ​
| Type Alias | Description |
|---|---|
| BandScaleOptions | Options for a band scale, controlling padding between and around bands, alignment, and rounding. |
| BaseElementState | Base state interface for all elements. All visual properties are optional at the element level. |
| BorderRadius | Four-corner border radius represented as [topLeft, topRight, bottomRight, bottomLeft]. |
| ColorHSL | An HSL color represented as a three-element tuple. |
| ColorHSLA | An HSLA color represented as a four-element tuple. |
| ColorHSV | An HSV color represented as a three-element tuple. |
| ColorHSVA | An HSVA color represented as a four-element tuple. |
| ColorInterpolator | A function mapping a normalized position (0–1) to a CSS color string. |
| ColorInterpolatorInput | Either a ready-made color interpolator or an array of color stops to interpolate between. |
| ColorRGBA | An RGBA color represented as a four-element tuple of channel values. |
| ColorSpace | Supported color space identifiers. |
| ContextFactory | The factory shape every rendering backend exports as createContext: target-first, with a backend-specific target and options type. Backends legitimately diverge on TTarget; DOM backends (canvas, SVG, 3D) accept a `string |
| Direction | Text direction for the rendering context. |
| Ease | An easing function that maps a linear progress value (0–1) to an eased output value. |
| ElementDefaults | Class-level defaults, applied beneath the options a caller passes. |
| ElementInterpolationKeyFrame | A single keyframe in a multi-step interpolation, with an optional offset (0–1) and a target value. |
| ElementInterpolationState | Partial state where each property can be a target value, keyframe array, or interpolator function. |
| ElementInterpolationStateValue | An interpolation target: a direct value, an array of keyframes, or a custom interpolator function. |
| ElementInterpolator | A factory able to interpolate a state value: one typed for the value itself, one typed for a single member of a union-typed value, or a universal factory such as interpolateAny. |
| ElementInterpolatorMember | A factory typed for a single member of a union-valued state property, so a `string |
| ElementInterpolators | A map of interpolator factories keyed by state property, used to override default interpolation behavior. A property may declare an ordered list, tried in order: the first factory whose test passes wins, and a property no factory claims falls back to interpolateAny. |
| ElementIntersectionOptions | Options for element intersection (hit) testing. |
| ElementOptions | Options for constructing an element, combining an optional id, CSS classes, data, pointer events, and initial state. |
| ElementPointerEvents | Controls which pointer events an element responds to during hit testing. |
| ElementValidationType | Severity level of an element validation result. |
| EventHandler | A callable event handler function with optional subscription options. |
| EventMap | Base event map interface; all custom event maps should extend this. |
| EventOptions | Options for emitting an event, controlling bubbling and attached data. |
| EventSubscriptionOptions | Options for subscribing to an event, such as filtering to self-targeted events only. |
| FillRule | Fill rule algorithm used to determine if a point is inside a path. |
| FontKerning | Font kerning mode for the rendering context. |
| Gradient | Union of all supported gradient types. |
| GradientBounds | Bounding rectangle a gradient's coordinates are resolved against. |
| GradientType | The discriminant string identifying a gradient's kind ('linear', 'radial', or 'conic'). |
| Interpolator | A function that interpolates between two values based on a normalized position (0–1). |
| InterpolatorFactory | A factory that creates an interpolator between two values of the same type, with a test predicate for type matching. |
| LineCap | Line cap style for stroke endpoints. |
| LineJoin | Line join style for stroke corners. |
| Matrix | A 2D affine transformation matrix stored as the six significant values of the augmented 3×3 matrix, in the same [a, b, c, d, e, f] order used by the Canvas 2D API (setTransform) and CSS matrix(): |
| MeasureTextOptions | Options for measuring text dimensions. |
| NavigatorInteractionOption | Enable/disable a single interaction, optionally with a sensitivity multiplier. |
| PathPoint | A sampled point on an SVG path with position and tangent angle. |
| PathRenderer | A callback that draws custom geometry onto a ContextPath using the element's state. |
| PatternTileShape | Union of the primitive shapes a pattern tile is composed of. |
| PatternType | The built-in pattern tile motifs available to pattern(...) paint strings. |
| Point | A 2D point represented as an [x, y] tuple. |
| PolylineRenderer | The name of a built-in polyline curve interpolation algorithm used to draw a polyline's points. |
| PolylineRenderFunc | A function that renders a polyline curve onto a path from an array of points. |
| PredicatedFunction | A callable with a test method used to determine whether the factory can handle a given value. |
| RenderElementPointerEvents | Controls which pointer events a render element responds to during hit testing. |
| RendererTransitionDirection | Alias for the transition playback direction within the renderer. |
| RendererTransitionOptionsArg | Transition options can be a static object or a per-element factory function. |
| RenderInstructionType | The kind of a RenderInstruction: enter a group boundary, draw a leaf, or exit a group boundary. |
| Rotation | Rotation value: a numeric radian value or a string with deg/rad suffix. |
| ScaleMethod | A function that maps a value from one space to another. |
| SceneEventMap | Event map for the scene. Resize is deliberately not re-emitted here; listen for it on the scene's context instead (scene.context.on('resize', …)), the single source of truth. |
| Shape2DDefaults | Class-level defaults for a 2D shape, adding the automatic fill/stroke and clipping flags to ElementDefaults. |
| Shape2DOptions | Options for a 2D shape, adding automatic fill/stroke and clipping controls. |
| StringInterpolationFormatter | Optional formatter applied to each interpolated numeric value before insertion into the output string. |
| StringInterpolationSet | A pair of tagged template results representing the start and end states for string interpolation. |
| TaskAbortCallback | Callback invoked when a task is aborted, receiving the abort reason. |
| TaskExecutor | Executor function for a task, providing resolve, reject, abort registration, and the underlying AbortController. |
| TaskReject | Callback to reject a task with an optional reason. |
| TaskResolve | Callback to resolve a task with a value or promise. |
| TextAlignment | Horizontal text alignment relative to the drawing position. |
| TextBaseline | Vertical text baseline used when rendering text. |
| TextOptions | Options for creating a text element within the context. |
| TransformOrigin | Transform origin value: a numeric pixel offset or a percentage string. |
| TransitionCallback | Callback invoked on each animation frame with the current eased time value (0–1). |
| TransitionDirection | The playback direction of a transition. |
| TransitionLoopMode | Controls whether a transition loops: true restarts from the beginning, 'alternate' ping-pongs direction each iteration. |
Variables ​
| Variable | Description |
|---|---|
| COLOR_SCHEME_BRBG | Diverging: brown → white → teal (ColorBrewer BrBG). |
| COLOR_SCHEME_CIVIDIS | Sequential: dark blue → slate → tan → yellow. Color-vision-deficiency friendly. |
| COLOR_SCHEME_INFERNO | Sequential: black → purple → red → orange → pale yellow. |
| COLOR_SCHEME_MAGMA | Sequential: black → purple → magenta → orange → cream. |
| COLOR_SCHEME_PLASMA | Sequential: dark blue → purple → magenta → orange → yellow. |
| COLOR_SCHEME_RDBU | Diverging: red → white → blue (ColorBrewer RdBu). |
| COLOR_SCHEME_TURBO | Sequential rainbow: purple → blue → cyan → green → yellow → orange → red. High contrast. |
| COLOR_SCHEME_VIRIDIS | Sequential: dark purple → blue → teal → green → yellow. The default perceptual scheme. |
| CONTEXT_OPERATIONS | Maps element state properties to their corresponding context setter functions. |
| DEFAULT_PATTERN_BACKGROUND | The default background color applied when a pattern string omits one. |
| DEFAULT_PATTERN_FOREGROUND | The default foreground color applied when a pattern string omits one. |
| DEFAULT_PATTERN_SIZE | The default tile size (in user-space pixels) applied when a pattern string omits one. |
| easeInBack | Back ease-in: retreats slightly before accelerating toward the target (a subtle anticipation). |
| easeInBounce | Bounce ease-in: accelerates with a series of diminishing bounces away from the start. |
| easeInCirc | Circular ease-in: accelerates from zero velocity along a circular arc. |
| easeInCubic | Cubic ease-in: accelerates from zero velocity. |
| easeInElastic | Elastic ease-in: winds up with decaying oscillation before springing toward the target. |
| easeInExpo | Exponential ease-in: accelerates from zero velocity with a sharp exponential curve. |
| easeInOutBack | Back ease-in-out: retreats before accelerating, overshoots, then settles back. |
| easeInOutBounce | Bounce ease-in-out: bounces away from the start then onto the target. |
| easeInOutCirc | Circular ease-in-out: accelerates then decelerates along a circular arc. |
| easeInOutCubic | Cubic ease-in-out: accelerates then decelerates. |
| easeInOutElastic | Elastic ease-in-out: winds up, springs across, and oscillates with decaying amplitude before settling. |
| easeInOutExpo | Exponential ease-in-out: accelerates then decelerates with a sharp exponential curve. |
| easeInOutQuad | Quadratic ease-in-out: accelerates then decelerates. |
| easeInOutQuart | Quartic ease-in-out: accelerates then decelerates. |
| easeInOutQuint | Quintic ease-in-out: accelerates then decelerates. |
| easeInOutSine | Sine ease-in-out: accelerates then decelerates along a sine curve. |
| easeInQuad | Quadratic ease-in: accelerates from zero velocity. |
| easeInQuart | Quartic ease-in: accelerates from zero velocity. |
| easeInQuint | Quintic ease-in: accelerates from zero velocity. |
| easeInSine | Sine ease-in: accelerates from zero velocity along a sine curve. |
| easeLinear | Linear easing: no acceleration or deceleration. |
| easeOutBack | Back ease-out: overshoots slightly past the target and settles back (a subtle spring). |
| easeOutBounce | Bounce ease-out: decelerates with a series of diminishing bounces before settling on the target. |
| easeOutCirc | Circular ease-out: decelerates to zero velocity along a circular arc. |
| easeOutCubic | Cubic ease-out: decelerates to zero velocity. |
| easeOutElastic | Elastic ease-out: springs past the target and oscillates with decaying amplitude before settling. |
| easeOutExpo | Exponential ease-out: decelerates to zero velocity with a sharp exponential curve. |
| easeOutQuad | Quadratic ease-out: decelerates to zero velocity. |
| easeOutQuart | Quartic ease-out: decelerates to zero velocity. |
| easeOutQuint | Quintic ease-out: decelerates to zero velocity. |
| easeOutSine | Sine ease-out: decelerates to zero velocity along a sine curve. |
| ELEMENT_INTERPOLATORS | The interpolators every element resolves its BaseState properties with, unless the element type or the caller declares otherwise. |
| EVENT_WILDCARD | The wildcard event type. Subscribing to it with EventBus.on receives every event emitted on the bus, whatever its type — including custom types a subclass never declares in EventBus.$events. Because events bubble, a wildcard subscription on a Group or Scene observes its whole subtree, with each event's target still identifying the bus it was originally emitted on. |
| factory | Global platform factory instance. Call factory.set(...) to provide environment-specific implementations. |
| HALF_PI | Quarter turn in radians (Ï€/2). |
| interpolateAny | Fallback interpolator factory that snaps from the first value to the second at the halfway point. |
| interpolateBorderRadius | Interpolator factory that transitions between two border-radius values (single number or four-corner tuple). |
| interpolateColor | Interpolator factory that smoothly transitions between two CSS color strings by interpolating their RGBA channels. |
| interpolateDate | Interpolator factory that interpolates between two Date instances by lerping their timestamps. |
| interpolateGradient | Interpolator factory that transitions between two CSS gradient strings by interpolating their stops, angles, and positions. |
| interpolateImage | Interpolator factory that cross-fades between two image sources using an offscreen canvas. |
| interpolateNumber | Interpolator factory that linearly interpolates between two numbers. |
| interpolateNumbers | Interpolator factory that transitions between two numeric arrays element-wise. |
| interpolatePattern | Interpolator factory that transitions between two pattern(...) paint strings sharing a tile type by interpolating their foreground/background colors and tile size. |
| interpolatePoints | Interpolator factory that transitions between two point arrays. By default it extrapolates additional points where set lengths differ; pass resolveKeys to match points by identity instead (preserving curved renderers across add/remove). |
| interpolateRotation | Interpolator factory that transitions between two rotation values (numbers in radians or strings like "90deg"). |
| interpolateTransformOrigin | Interpolator factory that transitions between two transform-origin values (numbers or percentage strings). |
| PATTERN_TYPES | The set of built-in pattern tile types accepted by pattern(...) paint strings. |
| scaleRGB | A continuous scale mapping normalized values (0–1) to the RGB channel range (0–255) with clamping. |
| TAU | Full circle in radians (2Ï€). |
| TRACKED_EVENTS | DOM event types that are tracked and forwarded to elements for hit testing and interaction. |
| TRANSFORM_DEFAULTS | Default numeric values for transform properties (translate, scale, rotation, transform-origin). |
Functions ​
| Function | Description |
|---|---|
| applyElementTransform | Applies an element's transform (translate, rotate, scale about its transform-origin) to the given target. Used both to drive a Context's transform during rendering and, via a matrix accumulator, to reconstruct an element's world transform for hit testing. |
| arePointsEqual | Tests whether two points have identical coordinates. |
| closest | Returns the closest ancestor (including the element itself) matching a CSS-like selector, or undefined. |
| computeTransitionTime | Computes the eased time value for a transition given elapsed time, duration, easing function, and direction. |
| createArc | Factory function that creates a new Arc instance. |
| createCircle | Factory function that creates a new Circle instance. |
| createElement | Factory function that creates a new Element instance. |
| createEllipse | Factory function that creates a new Ellipse instance. |
| createFrameBuffer | Creates a debounced requestAnimationFrame wrapper that cancels any pending frame before scheduling a new one. The returned scheduler carries a FrameBuffer.cancel handle so a pending frame can be dropped outright. |
| createGroup | Factory function that creates a new Group instance. |
| createImage | Factory function that creates a new ImageElement instance. |
| createLine | Factory function that creates a new Line instance. |
| createNumericIncludesMethod | Creates an includes predicate that tests whether a value falls within the numeric domain. |
| createPath | Factory function that creates a new Path instance. |
| createPolygon | Factory function that creates a new Polygon instance. |
| createPolyline | Factory function that creates a new Polyline instance. |
| createRect | Factory function that creates a new Rect instance. |
| createRenderer | Factory function that creates a new Renderer bound to the given scene. |
| createScale | Assembles a Scale object from explicit conversion, inversion, and tick functions. |
| createScene | Factory function that creates a new Scene instance from a context, selector, or element. |
| createShape | Factory function that creates a new Shape2D instance. |
| createText | Factory function that creates a new Text instance. |
| dataURLToBlob | Converts a base64 data URL into a Blob synchronously. |
| degreesToRadians | Converts degrees to radians. |
| elementIsArc | Type guard that checks whether a value is an Arc instance. |
| elementIsCircle | Type guard that checks whether a value is a Circle instance. |
| elementIsEllipse | Type guard that checks whether a value is an Ellipse instance. |
| elementIsImage | Type guard that checks whether a value is an ImageElement instance. |
| elementIsLine | Type guard that checks whether a value is a Line instance. |
| elementIsPath | Type guard that checks whether a value is a Path instance. |
| elementIsPolygon | Type guard that checks whether a value is a Polygon instance. |
| elementIsPolyline | Type guard that checks whether a value is a Polyline instance. |
| elementIsRect | Type guard that checks whether a value is a Rect instance. |
| elementIsShape | Type guard that checks whether a value is a Shape instance. |
| elementIsText | Type guard that checks whether a value is a Text instance. |
| getColorParser | Finds the first color parser whose pattern matches the given color string. |
| getContainingBox | Computes the smallest axis-aligned bounding box that contains all boxes extracted from the array. |
| getEuclideanDistance | Computes the Euclidean distance from two points. |
| getGradientBounds | Resolves the rectangle a gradient's coordinates map onto: the given bounding box, falling back to the full surface when no box is supplied or it has no area. |
| getLinearScaleMethod | Creates a linear mapping function from a numeric domain to a numeric range, with optional clamping and tick-padding. |
| getLinearTicks | Generates an array of evenly spaced, "nice" tick values across the domain. |
| getMidpoint | Returns the midpoint between two points. |
| getPadAngleAtRadius | Returns the angular inset, in radians, that trims an arc at radius back from a gap of padWidth logical pixels centred on the boundary angle — asin(padWidth / (2 * radius)). |
| getPadInnerRadius | Returns the smallest radius at which a sector of span radians still faces its neighbors with edges a full padWidth apart — (padWidth / 2) / sin(min(span, π) / 2). |
| getPathLength | Computes the total length of an SVG path from its d attribute string. |
| getPatternTileGeometry | Resolves the renderer-agnostic tile geometry for a pattern. Both the canvas and SVG backends draw the same primitive shapes, so a pattern renders identically across contexts. Diagonal lines extend beyond the tile bounds so the motif tiles seamlessly once clipped and repeated. |
| getPolygonPoints | Generates the vertex points of a regular polygon centered at (cx, cy) with the given radius and number of sides. |
| getThetaPoint | Returns the point at a given angle and distance from an optional center. |
| getTimeTicks | Generates calendar-aligned tick dates spanning [min, max] at roughly count ticks. |
| getWaypoint | Returns a point along the line segment between two points at the given normalized position (0–1). |
| hslToRGBA | Converts HSLA values to an RGBA tuple. |
| hsvToRGBA | Converts HSVA values to an RGBA tuple. |
| interpolateCirclePoint | Creates an interpolator that traces a point around a circle of the given center and radius. |
| interpolateColors | Builds a color interpolator from an array of color stops. Position 0 returns the first stop, 1 the last, and intermediate positions interpolate (RGBA, channel-wise) between adjacent stops. |
| interpolatePath | Creates an interpolator that progressively reveals a path from start to end as position advances from 0 to 1. |
| interpolatePolygonPoint | Creates an interpolator that traces a point around the vertices of a regular polygon. |
| interpolateString | Creates a string interpolator by interpolating between numeric values embedded in tagged template literals. |
| interpolateWaypoint | Creates an interpolator that returns the point along a polyline at the given normalized position. |
| isGradientString | Tests whether a string looks like a CSS gradient (starts with a recognized gradient function name). |
| isGroup | Type guard that checks whether a value is a Group instance. |
| isPatternString | Tests whether a string looks like a pattern(...) paint value (cheap shape check; use parsePattern to validate fully). |
| isPointInBox | Tests whether a point lies within the given bounding box (inclusive). |
| isTransparentColor | Determines whether a color string resolves to a fully transparent color. |
| matches | Tests whether an element matches a CSS-like selector. |
| matrixApplyToPoint | Applies matrix to the point [x, y], returning the transformed point. |
| matrixIdentity | Returns the identity matrix (a no-op transform). |
| matrixInvert | Returns the inverse of matrix, or null when it is singular (zero determinant) and therefore not invertible. |
| matrixIsIdentity | Tests whether matrix is the identity transform (within an exact comparison). |
| matrixMultiply | Post-multiplies a by b, returning the composite a · b. Applying the result to a point is equivalent to applying b first and then a, matching how successive translate/rotate/scale calls accumulate onto a canvas transform matrix. |
| matrixRotate | Returns a rotation matrix for the given angle, in radians. |
| matrixScale | Returns a scaling matrix with the given horizontal and vertical factors. |
| matrixTranslate | Returns a translation matrix that moves points by (x, y). |
| measureText | Measures the dimensions of a text string using an optional font and context override. |
| niceDomain | Returns the domain expanded to round, tick-aligned [min, max] boundaries. |
| normalizeBorderRadius | Normalizes a border radius value into a four-corner tuple, expanding a single number to all corners. |
| normalizePolylineRuns | Normalizes a polyline's segments into the contiguous, non-overlapping runs it is stroked in. |
| padDomain | Expands a numeric domain to "nice" tick-aligned boundaries and returns [min, max, step]. |
| parseColor | Parses any supported color string into an RGBA tuple, or returns undefined if nothing matches. |
| parseGradient | Parses a CSS gradient string (linear, radial, or conic) into a structured Gradient object, or returns undefined if the string is not a recognized gradient. |
| parseGradientCached | Parses a CSS gradient string via parseGradient, memoizing the result in a bounded LRU cache shared by every rendering backend. |
| parseHEX | Parses a hexadecimal color string in any CSS length (e.g. #f00, #f00c, #ff0000, #ff0000cc) into an RGBA tuple. |
| parseHSL | Parses an hsl() color string into an RGBA tuple. |
| parseHSLA | Parses an hsla() color string into an RGBA tuple. |
| parseHSV | Parses an hsv() color string into an RGBA tuple. |
| parseHSVA | Parses an hsva() color string into an RGBA tuple. |
| parseKeyword | Parses a CSS named color into an RGBA tuple, tolerating any casing and surrounding whitespace. |
| parsePattern | Parses a pattern(...) paint string into a structured Pattern object. |
| parsePatternCached | Parses a pattern(...) paint string via parsePattern, memoizing the result in a bounded LRU cache shared by every rendering backend. |
| parseRGB | Parses an rgb() color string into an RGBA tuple with alpha set to 1. |
| parseRGBA | Parses an rgba() color string into an RGBA tuple. |
| polylineBasisRenderer | Creates a cubic B-spline polyline renderer. |
| polylineBumpXRenderer | Creates a bump-X polyline renderer using horizontal midpoint bezier curves. |
| polylineBumpYRenderer | Creates a bump-Y polyline renderer using vertical midpoint bezier curves. |
| polylineCardinalRenderer | Creates a cardinal spline polyline renderer with configurable tension. |
| polylineCatmullRomRenderer | Creates a Catmull-Rom spline polyline renderer with configurable alpha. |
| polylineLinearRenderer | Creates a linear (straight segment) polyline renderer. |
| polylineMonotoneXRenderer | Creates a monotone-X polyline renderer preserving monotonicity along the x-axis. |
| polylineMonotoneYRenderer | Creates a monotone-Y polyline renderer preserving monotonicity along the y-axis. |
| polylineNaturalRenderer | Creates a natural cubic spline polyline renderer with second-derivative continuity. |
| polylineSplineRenderer | Creates a spline polyline renderer with configurable tension. |
| polylineStepAfterRenderer | Creates a step-after polyline renderer where the vertical transition occurs at the end of each segment. |
| polylineStepBeforeRenderer | Creates a step-before polyline renderer where the vertical transition occurs at the start of each segment. |
| polylineStepRenderer | Creates a step polyline renderer with midpoint horizontal transitions. |
| query | Returns the first element matching a CSS-like selector, or undefined if none match. |
| queryAll | Queries all elements matching a CSS-like selector across the given element(s) and their descendants. |
| radiansToDegrees | Converts radians to degrees. |
| rescaleDomain | Rescales a scale's domain to the window currently visible under a navigator transform. The scale maps data → the given pixel range; inverting the transformed range endpoints back through the scale yields the zoomed/panned data domain. This is how a cartesian chart turns navigator gestures into axis rescaling (scale.inverse) without transforming the rendered geometry. |
| resolveInteraction | Resolves a NavigatorInteractionOption to concrete values, defaulting a sensitivity that was not given to 1. |
| resolveNiceCount | Resolves a nice option to a target tick count (defaults to 10 when true). |
| resolvePolylineRenderer | Resolves a named curve algorithm (or a custom render function) to its render function. Defaults to linear. |
| resolveRotation | Resolves a rotation value (number, degrees string, or radians string) to radians. |
| resolveTransformOrigin | Resolves a transform-origin value (number or percentage string) to a pixel offset relative to the given dimension. |
| rgbaToHSL | Converts RGBA channel values to an HSLA tuple. |
| rgbaToHSV | Converts RGBA channel values to an HSVA tuple. |
| rgbChannelToHEX | Converts a single RGB channel value (0–255) to a two-character hexadecimal string. |
| samplePathPoint | Samples a point and tangent angle at the given distance along an SVG path. |
| scaleBand | Creates a band scale that maps discrete domain values to evenly spaced bands within the range. |
| scaleContinuous | Creates a continuous linear scale that maps a numeric domain to a numeric range. |
| scaleDiscrete | Creates a discrete (ordinal) scale that maps domain values to corresponding range values by index. |
| scaleDiverging | Creates a diverging scale that maps values below and above a midpoint to separate sub-ranges. |
| scaleLog | Shortcut for a base-10 logarithmic scale. |
| scaleLogarithmic | Creates a logarithmic scale that maps a numeric domain to a range using a log transformation. |
| scaleOrdinal | Creates an ordinal scale mapping each distinct domain value to a value from range, cycling when there are more domain values than range values. Unknown values encountered later are assigned the next range slot (so a chart can color series without pre-declaring every category). Unlike the numeric scales this maps value → value of any type; its most common use is categorical color. |
| scalePoint | Creates a point scale that maps discrete domain values to evenly spaced positions across the range (the categorical analogue of a continuous axis: points, not bands). With zero padding the first and last values sit exactly on the range endpoints. inverse returns the nearest domain value. |
| scalePower | Creates a power scale that maps a numeric domain to a range using an exponential transformation. |
| scaleQuantile | Creates a quantile scale that divides a sorted numeric domain into quantiles mapped to discrete range values. |
| scaleQuantize | Creates a quantize scale that divides a continuous numeric domain into uniform segments mapped to discrete range values. |
| scaleRadial | Creates a radial scale that maps a numeric magnitude to a ring radius. |
| scaleSequential | Creates a color scale mapping a numeric domain through a color interpolator (or array of stops, e.g. one of the built-in COLOR_SCHEME_* palettes). Values are clamped to the domain. |
| scaleSqrt | Shortcut for a power scale with exponent 0.5 (square root). |
| scaleSymlog | Creates a symmetric-log (symlog) scale that maps a numeric domain to a range through a sign-preserving logarithmic transform. |
| scaleThreshold | Creates a threshold scale that maps numeric values to range values based on a set of threshold breakpoints. |
| scaleTime | Creates a time scale that maps a Date domain to a numeric range using linear interpolation of timestamps. |
| serializeGradient | Serializes a structured Gradient object back into a CSS gradient string. |
| serializeHEX | Serializes RGBA channel values into a hexadecimal color string (e.g. #ff0000). |
| serializeHSL | Serializes RGBA channel values into an hsl() color string. |
| serializeHSLA | Serializes RGBA channel values into an hsla() color string. |
| serializeHSV | Serializes RGBA channel values into an hsv() color string. |
| serializeHSVA | Serializes RGBA channel values into an hsva() color string. |
| serializePattern | Serializes a structured Pattern object back into its canonical pattern(...) paint string. |
| serializeRGB | Serializes RGBA channel values into an rgb() color string. |
| serializeRGBA | Serializes RGBA channel values into an rgba() color string. |
| setColorAlpha | Returns a new color string with the alpha channel replaced by the given value. |
| transformBox | Transforms a box by an affine matrix and returns the axis-aligned bounding box of the result. Returns the box unchanged when matrix is null (the identity case). Because it re-fits an AABB around the transformed corners, a rotated box yields a conservative (enlarged) bounding box. |
| transition | Creates and starts a frame-driven transition that invokes the callback with the eased time on each animation frame. |
| typeIsContext | Type guard that checks whether a value is a Context instance. |
| typeIsElement | Type guard that checks whether a value is an Element instance. |
| typeIsPoint | Type guard that checks whether a value is a Point (a two-element array). |