Skip to content

Documentation / @ripl/canvas

@ripl/canvas ​

npmlicensesize

The Canvas 2D rendering context for Ripl: rasterizes the scene graph to an HTML <canvas> through CanvasRenderingContext2D.

Features ​

  • Ripl's default backend — implements the Context abstraction on the native Canvas 2D API, so the same drawing code also runs on SVG, the terminal or a custom context.
  • Device pixel ratio handled for you — the backing store scales with the display while every coordinate you author, every bounding box and every pointer payload stays in CSS pixels.
  • Native paint objects — CSS gradient and pattern strings in fill and stroke are parsed and cached into CanvasGradient and CanvasPattern instances, keyed so repeated paints reuse them.
  • Browser hit testing — isPointInPath/isPointInStroke run against the browser's own implementation, under both fill rules.
  • Path2D caching — supportsPathCaching is true here, so a shape whose state has not changed replays its built path instead of re-tracing it each frame.
  • Text along a path and full stroke/fill state: caps, joins, dashes, miter limit, shadows, filters and blend modes.
  • Snapshot export — PNG data URL, Blob object URL, or raw ImageData.

Installation ​

Most browser projects should install @ripl/web instead. It re-exports this package alongside @ripl/core and registers the browser platform bindings, which this context needs for text measurement and frame scheduling.

bash
# npm
npm install @ripl/canvas

# yarn
yarn add @ripl/canvas

# pnpm
pnpm add @ripl/canvas

Quick start ​

typescript
import {
    createContext,
} from '@ripl/canvas';

import {
    createCircle,
} from '@ripl/core';

const context = createContext('.mount-element');

createCircle({
    fill: 'linear-gradient(135deg, #3a86ff, #8338ec)',
    cx: context.width / 2,
    cy: context.height / 2,
    radius: 50,
}).render(context);

Every context can snapshot its current output through export():

typescript
const snapshot = context.export();

const dataUrl = snapshot.toString(); // PNG data URL
const url = snapshot.toURL(); // PNG object URL
const image = await snapshot.toImage(); // ImageData

snapshot.release(); // revokes the object URL

Key API ​

ExportWhat it does
createContextBinds a CanvasContext to a selector, element or existing canvas
CanvasContextThe context itself, for typing and subclassing
CanvasPathPath2D-backed path builder used by every element
toCanvasGradient / toCanvasPatternPaint-string conversion into native canvas paints
rescaleCanvasResizes the backing store for a device pixel ratio
  • @ripl/web — the browser entry point, and what most projects should install
  • @ripl/core — the elements and scene graph this context draws
  • @ripl/svg — the same API, rendering to SVG instead
  • @ripl/3d — a 3D context built on this one

Documentation ​

Guides, live demos and the full API reference are at ripl.run/docs/core/contexts/canvas.

License ​

MIT

Classes ​

ClassDescription
CanvasContextCanvas 2D rendering context implementation, mapping the unified API to CanvasRenderingContext2D.
CanvasPathCanvas-specific path implementation backed by a native Path2D object.

Interfaces ​

InterfaceDescription
Canvas2DStateThe shared CanvasRenderingContext2D state-plumbing surface applied by canvas2DStateMixin: paint, line, shadow, and text accessors mapped directly onto the native 2D context, plus the drawing, transform, measurement, and hit-testing operations common to every canvas-backed context.
RescaleResultResult of a canvas rescale operation containing the updated coordinate scales.

Type Aliases ​

Type AliasDescription
AbstractConstructorConstructor type for (possibly abstract) classes, used to compose mixins over a Context base.

Functions ​

FunctionDescription
applyCanvasFillFills a canvas path or text element, dispatching text-along-path when applicable.
applyCanvasStrokeStrokes a canvas path or text element, dispatching text-along-path when applicable.
canvas2DStateMixinMixin applying the shared CanvasRenderingContext2D state plumbing (see Canvas2DState) to a Context base class. Concrete subclasses assign the protected context backing field (declared here, so constructor assignment is not clobbered by class-field initialization) and may override the protected gradientBounds() hook to change which bounding box gradients resolve against; the default is the current render element's local (untransformed) box.
canvasDrawImageDraws an image onto a canvas context, sizing it to the given width and height.
canvasIsPointInPathTests whether a point is inside the filled region of a canvas path.
canvasIsPointInStrokeTests whether a point is on the stroked outline of a canvas path.
canvasMeasureTextMeasures text dimensions using the context's alignment and baseline, and an optional font override.
createContextCreates a Canvas 2D rendering context (a concrete Context) attached to the given DOM target.
releaseCanvasPaintCacheDrops every CanvasGradient and CanvasPattern cached against a context, together with the offscreen tile canvases the patterns hold. Call it when the context is torn down.
renderTextAlongPathRenders text character-by-character along a path using fill or stroke.
rescaleCanvasSizes a canvas element's backing store for the device pixel ratio and returns the coordinate scales mapping logical pixels onto it.
setCanvasFillSets the fill style on a native canvas context, resolving gradient and pattern strings when applicable.
setCanvasStrokeSets the stroke style on a native canvas context, resolving gradient and pattern strings when applicable.
toCanvasGradientConverts a parsed gradient definition into a native CanvasGradient within the given bounds.
toCanvasPatternMaterializes a pattern(...) paint string as a repeating CanvasPattern, drawing the shared tile geometry into an offscreen canvas. Results (including parse failures) are cached per context and string, and released by releaseCanvasPaintCache.