Public package reference · fastplotjs@0.3.0

Chart types and options

Choose a chart family, shape its data, and configure the plot. These fields come from the published package. Each family links to a live example in the chart gallery. Browser methods and events have a separate API reference.

Start here

One Canvas, one chart

Install fastplotjs@0.3.0 in a browser project with a bundler. createChart accepts an HTML Canvas, chart options, and an optional Canvas fallback style. Its instance owns rendering and cleanup. The TypeScript engine needs no optional Rust initialization.

<canvas id="chart" width="800" height="360"></canvas>
<script type="module">
  import { createChart } from "fastplotjs";
  const chart = createChart(document.getElementById("chart"), {
    type: "line", engine: "ts",
    data: [{ x: 0, y: 4 }, { x: 1, y: 7 }, { x: 2, y: 5 }],
    axes: { show: true },
  });
  // Call chart.destroy() when this Canvas is removed.
</script>

plot({ type, width, height, data }) creates a renderer-neutral scene without a browser. In createChart, width and height are optional; in plot they are required. Both are Canvas pixels. Runtime and export details

Input contract

Data and validation

Supply data: DataPoint[] for one series or traces: TraceInput[] for named, styled series. A trace has required data and optional name, visible, color, xAxis, yAxis, and subplot. Trace options override corresponding plot-level family settings where supported.

Point fieldUse
x, yRequired scalar positions. A scalar is a number, string, or Date; null represents a gap where supported. Match axis scale and family data shape.
baseOptional bar baseline.
valueHeatmap cell value or point color input in wonderplot and scatter3d.
zThird coordinate for experimental 3D families; alternative color/value input for heatmap and wonderplot.
size, opacityOptional per-point scale inputs for wonderplot and scatter3d.
xError, yErrorCartesian error magnitude: a number or { minus, plus }. Supported for line, grouped bar value axes, and wonderplot, with bar orientation/stacking restrictions.

Use finite numbers for numeric positions and values. Logarithmic domains and color scales require positive values. Explicit category arrays establish stable order; datetime inputs normalize to time values. Invalid topology, malformed values, unsupported scale combinations, and unavailable engines fail. Event point indices refer to original input positions; LOD can omit rendered points.

Per-trace option groups are lineStyle, areaFill, markers, pointLabels, errorBars, bar, heatmap, polar, wonderplot, scatter3d, line3d, surface, mesh3d, trendline, polarVector, and connectGaps. Apply a group only to its compatible family.

PlotOptions / ChartOptions

Shared configuration

FieldMeaning
typeRequired: line, bar, polar, pie, heatmap, wonderplot, scatter3d, line3d, surface, mesh3d, or pie3d.
data / tracesSingle or multiple input series.
width, heightPixel dimensions: required for plot, optional for createChart.
engineauto (default), ts, or rust. Rust requires separately initialized compatible Node or WASM capability; experimental 3D rejects Rust.
title, subtitle, titleStyle, subtitleStyleOptional headings and text style.
style, backgroundColor, plotAreaBackgroundColorGlobal style tree and direct background aliases.
axes, subplots, viewport, margin, legendCoordinates, layout, initial view, outer pixel margins, and series key.
referencesCartesian reference lines and bands.
lineStyle, areaFill, markers, pointLabels, errorBars, trendline, connectGapsLine-related plot defaults, with compatible trace overrides.
bar, polar, pie, pie3d, heatmap, wonderplot, scene3d, scatter3d, line3d, surface, mesh3dFamily-specific groups detailed below.

Omitted optional values use package defaults. Boolean shorthand such as legend: true or markers: true enables its default configuration; nested objects override individual fields.

New in 0.3.0

Canvas display quality

Control pixel density independently of layout for every 2D chart and Canvas-rendered 3D chart. Automatic DPR and supersampling sharpen text and edges without changing logical sizes or pointer coordinates.

createChart(canvas, {
  type: "pie3d",
  pie: { data: [{ label: "A", value: 5 }, { label: "B", value: 3 }] },
  canvas: { pixelRatio: "auto", resolutionScale: 2 },
  pie3d: { curveTolerance: 0.1 },
});
OptionDefaultEffect
canvas.pixelRatio1A positive finite number, or "auto" for the current devicePixelRatio.
canvas.resolutionScale1A positive supersampling multiplier applied to pixelRatio.
pie3d.curveTolerance1 logical pixelSmaller values make experimental Pie3D curves more detailed, within the existing scene3d.maxPoints budget.

Backing dimensions are rounded from logical dimensions multiplied by both ratios. More pixels use more memory and rendering work; explicit quality settings reject backing buffers over 16,384 pixels per edge or 67,108,864 pixels total. Native 2D arcs need no polygon-detail option. WebGL2 offscreen resolution and PNG export resolution are unchanged.

createChart handles resize and automatic DPR changes. renderToCanvas re-reads DPR on every call and accepts optional logical width and height for direct resizing. Canvas attributes expose backing pixels; layout and event coordinates remain logical pixels. Existing omitted options keep the previous 1:1 resolution.

Compare 2D and Pie3D before and after, including direct Canvas rendering.

Omitted values

Key defaults and units

These are the consumer-visible defaults in 0.3.0; the option lists below give the remaining overrides. Optional minValue/maxValue generally infer a domain from valid data when omitted. A false boolean or an omitted opt-in group leaves that feature disabled. Styles inherit through plot and trace settings.

AreaDefault when omitted
Engine and 3D rendererengine: "auto"; scene3d.renderer: "canvas". Strict "webgl2" fails without WebGL2; "auto" may fall back to Canvas.
Barmode: "grouped", orientation: "vertical", barWidthRatio: 0.72; value labels off.
Polarmode: "windrose", linear radius, grouped sectors, sectorWidthDegrees: 24, startAngleDegrees: -90, clockwise true; grid, labels, and vectors off.
PieClockwise sectors from −90°, no gap, full outer radius, no inner radius; labels off.
Pie3Dpie3d.extrusionDepth: 0.15 normalized scene units; one full-chart scene, Canvas renderer, and camera controls shared with other experimental 3D families.
HeatmapLinear color scale, lowColor: "#e0f2fe", highColor: "#0369a1", cellGap: 0, cornerRadius: 0; missing cells, cell labels, guides, and color legend off.
WonderplotCircle markers, markerSize: 5 pixels, markerOpacity: 1; size/opacity scales and marker labels off.
Scatter3DCircle markers, markerSize: 6 pixels, markerOpacity: 0.9; LOD and per-point size/opacity scales off. If enabled without an explicit budget, spatial-grid LOD uses maxPoints: 5000.
Line3DLinear interpolation, lineWidth: 2 pixels, lineOpacity: 1; LOD off, or maxSourceSegments: 250 if enabled without a budget.
SurfacemissingCells: "gap", opacity: 1, wireframe/contours/LOD off; if enabled without a budget, grid-stride LOD uses maxCells: 10000.
Mesh3Dopacity: 0.82, backface culling/wireframe/LOD off; if enabled without a budget, largest-area-stratified LOD uses maxFaces: 1000.
3D camera and accessibilityPerspective camera, 45° field of view, visible axes/grid, lighting off, accessibility opt-in. The scene limit defaults to maxPoints: 100000.
Browser interactionsZoom, pan, rotation, camera controls, tooltip, crosshair, click, and selection are opt-in. Drag mode defaults to zoom. The tooltip defaults to one point (not shared); crosshair is xy with free-pointer snap when enabled.

Widths, gaps, radii, offsets, font sizes, and pointer thresholds are Canvas pixels unless a field says degrees, ratio, opacity, or data units. Explicit range, minValue/maxValue, and point coordinates use their corresponding data units.

Coordinates and layout

Axes, viewports, and subplots

axes.show turns on Cartesian axes. Global labelStyle, lineStyle, and gridStyle use font/color/lineHeight or color/lineWidth. Named xAxes and yAxes map ids to per-axis options; x axes can use side: "top" | "bottom", y axes "left" | "right". Bind a trace with xAxis and yAxis.

Per-axis fields: show, title, titleStyle, labelStyle, lineStyle, gridStyle, grid, scale (linear, logarithmic, datetime), range, padding, viewportGroup, ticks, tickValues, tickLength, tickDirection, labelPrefix, labelSuffix, labelRotationDegrees, labelCollision, labelFormatter, decimals, categories, dateTime, minor, and minorLogLabels. minor has show/ticks/ticklen/grid; dateTime has timeZone/format. padding is a percent or { start, end }; range uses { min, max }. Axis label formatters receive value, default label, axis id, dimension, scale, and major/minor flags; return a string or null to suppress a label.

tickLength defaults to 5 pixels and tickDirection to outside. Rotation is Canvas degrees, clamped to −90…90; labelCollision defaults to allow. Datetime values use Unix milliseconds internally; dateTime.timeZone accepts browser, utc, or an Intl timezone. Log scales require positive ranges. Categorical axes use configured string categories.

subplots.layout sets rows and columns as counts or weighted track arrays (id, weight), plus pixel rowGap/columnGap. subplots.items maps subplot ids to zero-based row/column, optional rowSpan/columnSpan, and axis ids. Bind traces to a subplot id. Initial viewport.xAxes/yAxes maps axis ids to { min, max }. A matching viewportGroup links compatible axes within one dimension; mismatched scales or categories fail.

references.lines accepts axis/value/axisId/subplot/color/lineWidth/pattern/label/labelStyle; references.bands accepts axis/from/to/axisId/subplot/fillColor/label/labelStyle. Line patterns are solid, dashed, dotted, or dash-dot.

axes: { show: true,
  xAxes: { time: { scale: "datetime", dateTime: { timeZone: "utc" } } },
  yAxes: { value: { side: "right", title: "Units" } } },
traces: [{ data: [{ x: new Date("2026-01-01"), y: 4 }],
  xAxis: "time", yAxis: "value" }]
Presentation

Styles, margins, and legends

style holds backgroundColor, text, title, subtitle, plotArea.backgroundColor, axes.label/line/grid, trace.line/marker/area, legend, and tooltip. Text style has font/color/lineHeight; stroke style has color/lineWidth. Trace line style has color/lineWidth/opacity/interpolation/pattern; marker style has show/size/color/shape; area style has show/color/opacity. Direct plot and trace options refine broad defaults. margin uses l/r/t/b in pixels.

legend: true displays the standard legend. Object fields: show, position (top-left, top-right, bottom-left, bottom-right, outside-bottom), layout (column/row), groupBy (none/subplot), interactive, isolateOnDoubleClick, groups, and style. A custom group has label and entries; each entry has label and traceIndexes. interactive defaults to true and isolateOnDoubleClick is opt-in. Legend clicks keep at least one trace visible.

legend.style has text, groupTitle, backgroundColor, borderColor, borderWidth, padding. Direct aliases textStyle, groupTitleStyle, backgroundColor, borderColor, borderWidth, and padding are also accepted on legend. Tooltip style has text/backgroundColor/borderColor/borderWidth/borderRadius/padding. Optional third createChart argument, CanvasRenderOptions, has color and lineWidth.

Cartesian series

Line

Use ordered { x, y } points for trends. Live line demo · step-by-step guide. lineStyle sets color, pixel width, opacity, interpolation (linear, smooth, step-before, step-after, step-center), and pattern. connectGaps joins valid points across null gaps when enabled.

markers accepts a boolean or show/size/color/shape; shapes are circle, square, diamond, triangle, pentagon, or hexagon. areaFill accepts show/color/opacity/baseline; baseline is axis-min, axis-max, zero, or a scalar. pointLabels accepts show/color/font/lineHeight/position/offset/decimals/prefix/suffix/collisionPadding/formatter; position is above, below, or auto. errorBars accepts show/x/y/color/lineWidth/capSize and reads point xError/yError. trendline accepts show/method/degree/samples/color; methods are linear, polynomial, exponential, logarithmic, power, gaussian, and cauchyLorentz. Formatter callbacks receive source context. Nonlinear methods require compatible values.

Line options can be given at plot level and overridden per trace. Cartesian viewport zoom and pan are available when enabled in interactions.

Categorical comparison

Bar

Use category/value points for grouped, stacked, or normalized bars. Live bar demo. bar.mode is grouped, stacked, or normalized; orientation is vertical or horizontal. barWidthRatio controls slot width. Plot and trace bar options include borderColor, borderWidth, cornerRadius, and valueLabels. A point can provide base for its baseline.

valueLabels accepts a boolean or show/color/font/position/offset/decimals/prefix/suffix/minBarWidth/minBarHeight/formatter. Position is center, inside-end, or outside-end; minimum dimensions and offsets are pixels. The formatter receives raw value, baseline, optional normalized value, orientation, mode, trace index, and source index. Normalized mode reports percentage-space geometry while retaining raw point values in inspection events. Vertical bars use y as value and horizontal bars use x; a floating base follows that value axis. On a linear value axis, grouped bars can mix explicit bases with omitted/null bases, which resolve to zero. On logarithmic or datetime value axes, every non-null grouped point needs an explicit base; logarithmic endpoints must both be positive. Stacked and normalized bars require a linear value axis and do not support floating bases.

Bar supports tooltip, crosshair, click, selection, and legend behavior. Axis viewport zoom interactions and zoom helpers are no-ops for bar; do not build bar navigation around zoomIn(). Direct setViewport() can still update stored viewport state and emit viewportChange.
Directional values

Polar wind rose

Use angle/value pairs with type: "polar" and polar.mode: "windrose". Live polar demo. radialScale is linear or logarithmic; sectorMode is grouped or stacked. angleCategories fixes directional labels; sectorWidthDegrees, startAngleDegrees, clockwise, innerRadiusRatio, outerRadiusRatio, minRadius, and maxRadius control geometry. Angles are degrees; radius ratios are fractions.

Plot/trace sector fields are sectorGapDegrees, sectorOpacity, borderColor, borderWidth, and sectorLabels. Sector labels accept show/color/font/lineHeight/decimals/prefix/suffix/minSectorRadius/minSectorAngleDegrees/radiusRatio/collisionPadding/formatter. polar.grid accepts show/rings/ringValues/spokes/ringColor/spokeColor/ringLineWidth/spokeLineWidth/labels/angleLabels. Radial labels accept show/color/font/decimals/angleDegrees/offset/prefix/suffix/formatter; angle labels accept show/color/font/decimals/offset/labels/prefix/suffix/formatter. Callback arguments include default label and relevant value, angle, index, scale, category, or source identity.

Stacked sectors cannot use a logarithmic radial scale; that combination fails closed. polar.vectors or trace polarVector accepts show/directions/color/lineWidth/headSize/headAngleDegrees. Each direction is a degree number or object with direction (alias directionDegrees) and optional style. Browser rotation is opt-in through interactions.polarRotate; Cartesian viewport zoom does not apply.

Two-dimensional grid

Heatmap

Supply { x, y, value } cells (z is an alternative value input); optional xCategories/yCategories set order. Live heatmap demo · step-by-step guide. heatmap.valueScale is linear or logarithmic; logarithmic color values must be positive. Choose lowColor/highColor or colorStops of { offset, color }, with optional minValue/maxValue. A custom scale needs at least two strictly increasing stops, exact 0 and 1 endpoints, and #RGB or #RRGGBB hex colors.

Plot/trace cell fields are cellGap, cornerRadius, borderColor, borderWidth, missingCells, and cellLabels. Gap/radius/border widths are pixels. missingCells accepts show/fillColor/borderColor/borderWidth. cellLabels accepts show/color/font/lineHeight/padding/decimals/prefix/suffix/minCellWidth/minCellHeight/formatter; formatter receives value, category/position, row/column, trace and source index.

xLabels/yLabels accept a boolean, string array, or show/labels/color/font/lineHeight/offset. guides accepts show/color/lineWidth. colorScaleLegend accepts show/position/title/width/height/offset/tickCount/tickValues/tickSize/labelGap/labelPrefix/labelSuffix/decimals/color/font/lineHeight/titleGap/borderColor/borderWidth. Position is left, right, top, or bottom. Generated missing cells are display-only and not selectable source records.

Multi-attribute scatter

Wonderplot

Use { x, y, value, size, opacity } to map several attributes to markers; z is an alternative color-value input. Live wonderplot demo. Plot and trace fields include markerSize, markerOpacity, markerShape, markerLabels, borderColor, and borderWidth. Shape uses the six shared marker shapes. Marker labels accept show/color/font/lineHeight/decimals/prefix/suffix/offsetY/collisionPadding/formatter.

colorScale accepts valueScale/lowColor/highColor/colorStops/minValue/maxValue. sizeScale accepts a boolean or enabled/minSize/maxSize/minValue/maxValue; opacityScale accepts a boolean or enabled/minOpacity/maxOpacity/minValue/maxValue. Marker sizes are pixels; opacity is 0…1. colorScaleLegend has the same presentation fields as the heatmap legend (show/position/title/width/height/offset/tickCount/tickValues/tickSize/labelGap/labelPrefix/labelSuffix/decimals/color/font/lineHeight/titleGap/borderColor/borderWidth). Log color scales require positive values. Cartesian viewport controls are available.

Part-to-whole

Pie and donut

Use type: "pie" with pie.data or pie.traces containing { label?, value }. Positive values create source-ordered sectors; zero and null are omitted, while negative and non-finite values fail. The original trace and datum index survive legend filtering and inspection. Live Pie demo.

pie accepts startAngleDegrees, clockwise, sectorGapDegrees, innerRadiusRatio (0…0.95), outerRadiusRatio (0.05…1), colors, sectorOpacity, hiddenDataIndexes, borderColor, borderWidth, and labels. Set an inner radius above zero for a donut. Labels accept content (label, value, fraction, label-value, label-fraction), position, decimals, affixes, visibility threshold, and formatter. Data and trace options are shared with Pie3D; explicit 2D border color/width are unsupported there.

Experimental 3D

Scatter3D

Supply finite numeric { x, y, z } points; a null coordinate omits that marker. Optional point value, size, and opacity feed color, radius, and alpha scales. Enabling a color, size, or opacity scale requires its corresponding finite point field on every visible complete point. Live Scatter3D demo. Plot and trace fields are markerSize, markerOpacity, and markerShape. Plot-level colorScale has valueScale/lowColor/highColor/colorStops/minValue/maxValue; sizeScale has enabled/minSize/maxSize/minValue/maxValue; opacityScale has enabled/minOpacity/maxOpacity/minValue/maxValue. colorScaleLegend is boolean.

lod accepts a boolean or { enabled, strategy: "spatial-grid", maxPoints }. Opt-in LOD chooses representative rendered points while retaining full-source domains. Rendered inspection carries source indices; it is not a query of omitted source points. Use shared 3D scene controls.

Experimental 3D

Line3D

Supply ordered finite numeric { x, y, z } points; a null coordinate separates runs. Smooth interpolation never bridges that gap. Live Line3D demo. Plot/trace options lineWidth (pixels), lineOpacity (0…1), and interpolation (linear/smooth) style segments. Plot maxSegments bounds output. lod accepts a boolean or { enabled, strategy: "largest-triangle-3d", maxSourceSegments }. LOD is opt-in and operates per null-separated run, retaining endpoints and source metadata. Use shared 3D scene controls.

Experimental 3D

Surface

Provide exactly one { x, y, z } sample for each x/y slot of a rectangular regular grid. Coordinates are finite numbers; missing heights may be represented and handled as gaps or zero-height cells by missingCells. Duplicate or missing grid slots fail validation. Live surface demo. surface accepts lowColor/highColor/colorStops/minValue/maxValue for height color, opacity, wireframe, contours, lod, missingCells (gap/zero), maxTriangles, maxContourSegments, and boolean colorScaleLegend. Trace overrides are opacity/wireframe/contours.

Wireframe is boolean or { show, color, width, opacity }; contours are boolean or { show, values, count, color, width, opacity }. Widths are pixels, opacity is 0…1. lod is boolean or { enabled, strategy: "grid-stride", maxCells }; it is opt-in and preserves full-source domains while reducing prepared cells. Triangle and contour caps limit allocation. Use shared 3D scene controls.

Experimental 3D

Mesh3D

Supply finite numeric { x, y, z } vertices and triangular face index triples. Live Mesh3D demo. mesh3d.faces is an array of [a, b, c] zero-based vertex indices. Optional faceColors and vertexColors are mutually exclusive; each needs one #RGB/#RRGGBB hex color per face or vertex respectively. Plot/trace fields are faces/faceColors/vertexColors/opacity/backfaceCulling/wireframe; plot adds maxFaces and lod. Malformed, degenerate, duplicate-index, or out-of-range faces fail validation.

Wireframe uses the same show/color/width/opacity fields as Surface. lod is boolean or { enabled, strategy: "largest-area-stratified", maxFaces }; it is opt-in, retains source-face identity for kept faces, and does not return skipped faces through selection. Opacity is 0…1. Use shared 3D scene controls.

Experimental 3D

Pie3D

type: "pie3d" reuses Pie data, sector colors, gaps, labels, trace/datum legends, and tooltip/click source identity. It projects extruded top, bottom, outer, inner-donut, and radial faces through the shared 3D camera and depth picker. Live Pie3D demo. pie3d.extrusionDepth is the vertical depth in normalized scene units, defaults to 0.15, and must be finite within (0, 1]; zero is invalid. Camera tilt changes apparent height. Complex translucent overlap may not sort perfectly.

Pie3D occupies one full-chart scene. Named or mixed subplots, Cartesian viewport/axis options, 2D Pie border color/width, and Rust geometry are unsupported. Shared scene3d.camera, optional lighting, Canvas/WebGL2 renderer selection, static SVG, and optional native Node PNG apply.

Shared experimental controls

3D scene and limits

scene3d.renderer defaults to canvas; strict webgl2 fails if unavailable, while auto can fall back to Canvas. Resolution and fallback are reported in scene diagnostics. scene3d.subplots maps named ids to isolated 3D settings. Global and subplot settings include camera, xAxis/yAxis/zAxis, showAxes/showGrid/gridSteps/axisColor/gridColor/axisLineWidth/gridLineWidth/maxPoints/accessibility. lighting is available for Surface, Mesh3D, and Pie3D; enabling it on Scatter3D or Line3D fails closed.

Camera fields: projection (perspective/orthographic), eye/target/up as three-number tuples, fieldOfViewDegrees, orthographicScale, near, and far. Axis fields: range, padding, show, title, showTickLabels, tickCount, tickDecimals. Lighting accepts a boolean or show/direction/ambient/diffuse/specular/shininess/twoSided. Accessibility is opt-in (disabled by default), accepts a boolean or enabled/label/description/maxRows/includeTable, and provides source-row summary and optional fallback table. Angles are degrees; 3D domains are linear numeric ranges.

All five 3D families are experimental and use TypeScript geometry with engine: "auto" | "ts". engine: "rust" fails explicitly. Mixed 2D/3D scenes and browser-native PNG export are not promised. Static Node scenes and SVG export are available; real 3D PNG needs optional native Node capability. Runtime and export reference.