API reference
Methods, defaults, and practical limits in one place.
Imports
| Entrypoint | Exports |
|---|---|
portalgl | DynamicCanvas, TrackedElement, TrackingContext, findStickyAncestor, tracking/projector types, and VERSION |
portalgl/track | The same tracking API, without VERSION |
portalgl/three | ThreeDOM, ThreeProjector, projection helpers and types, plus the tracking API |
Core does not load React or Three.js. ESM and CommonJS are supported. Construct controllers in the browser after mounting; imports are safe on the server.
PortalGL manages element measurements automatically. Controllers and trackers release their measurements on destruction without affecting other controllers.
ThreeDOM
const dom = new ThreeDOM({ renderer, container, maxPixelRatio: 2 })
| Constructor option | Requirement / default |
|---|---|
renderer | Initialized WebGPURenderer; one coordinator per renderer |
container | Element the shared canvas goes in, as its first child; see WebGL2 fallback |
maxPixelRatio | 2; positive, finite device-pixel-ratio cap |
clipPadding | 0.25; default padding per edge for view clips |
| Method | Purpose |
|---|---|
addView(element, options) | Register an independent view; returns ThreeView |
addScene(options) | Register a shared scene; returns ThreeScene |
update(time?) | Place content, call registered onFrame callbacks, and render |
advance(time?) | Place content without running callbacks or rendering |
render() | Draw the current composition without running onFrame |
prepare({ signal? }?) | Prepare sized views; returns a promise for their count |
setContainer(element) | Move the shared canvas into another element at the next frame |
destroy() | Release all registrations and owned resources; safe to repeat |
dom.mode is 'multi-canvas' on native WebGPU and 'shared-canvas' on the WebGL2
fallback; dom.container is the shared canvas's element.
time is milliseconds and defaults to performance.now(). onFrame receives
{ time, delta }, where delta is seconds, capped at 0.1 and zero on the first
tick or after reactivation. Copy values if retaining them; the frame object is reused.
prepare() does real draws but does not run onFrame. Pause the loop while it
runs. An AbortSignal can cancel it; await settlement before disposing assets.
After a failed preparation, retry or remove the affected views before resuming.
Registration options
Both methods require scene and a unique perspective camera.
| Option | Purpose / default |
|---|---|
pipeline | Optional RenderPipeline created with the same renderer; one graph per registration |
scrollMargin | 0.15 viewport heights above and below the viewport |
onFrame | Animation callback; at most one owner per scene |
onActive, onInactive | Rendering-eligibility transitions; no initial replay |
clip | Views only: an additional DOM clipping rectangle |
clipPadding | Views only: override the coordinator's clip padding |
order | Views only: 0; stacking on the WebGL2 shared canvas, higher on top |
ThreeView exposes tracked, optional clip, mutable clipPadding, order and
scrollMargin, active, and destroy(). ThreeScene exposes track(),
bindings, mutable scrollMargin, active, and destroy(). Both expose their
scene, camera, and optional pipeline.
Their on('active' | 'inactive', callback) methods return unsubscribe functions.
Views stop drawing outside their margin or when fully clipped. Shared scenes can
remain eligible because of backgrounds, pipelines, or custom render hooks.
dom.views, dom.scenes, and dom.registrations are live, readonly arrays.
Registrations contain { type: 'view' | 'scene', slot }. Do not mutate the arrays;
copy them before removing items during iteration.
Object and quad bindings
| Call | Result |
|---|---|
world.track(element, object, { depth, fill, clip }) | Position a scene object; defaults: depth: 4, fill: 1, clip: true |
world.track(element, { depth }) | Track a full rectangle for quad meshes; default depth: 4 |
binding.bindQuad(mesh) | Bind a centered unit XY mesh; returns a mesh-specific cleanup handle |
binding.destroy() | Release the tracker and meshes; restore borrowed transforms |
depth is positive camera-local distance. fill is a non-negative multiplier for
a unit-size object's fit to the smaller DOM dimension. Options are fixed at
registration; recreate a binding to change them.
Use binding.tracked for DOM state, binding.quad for the read-only world-space
rectangle, and binding.valid to check whether projection bounds are ready.
Destroying a binding never removes scene objects or disposes assets.
TrackedElement and TrackingContext
Create new TrackingContext(), then
new TrackedElement({ source, element }). One source can serve many trackers.
| Member | Purpose |
|---|---|
tracked.rect | Cached viewport-space { left, top, width, height }, or null |
tracked.state | Current el, stickyKind, pinned, and active |
tracked.setElement(element | null) | Rebind or detach |
tracked.refresh() | Queue fresh bounds and rediscover sticky ancestry; returns void |
tracked.on('bounds', callback) | Rectangle changes, including scroll and detachment |
tracked.on('update', callback) | Changes to the tracked element or its state |
source.update() | Flush measurements and sample scroll for all trackers |
source.refresh() | Refresh sticky observations and signal geometry changes |
source.destroy() | Release this source and its trackers |
on() returns an unsubscribe function. Destroying a tracker or source releases
its measurements without affecting other clients. A sticky tracker's active
means pinned, not visible.
DynamicCanvas
new DynamicCanvas(options) uses native window scroll and resize sources by
default and manages element measurements automatically.
| Option | Default |
|---|---|
canvas | Optional; bind one later with bindCanvas(canvas) |
viewportElement | Optional fullscreen ruler; does not create a nested scroll root |
defaultMode | 'absolute' |
padding | 0.25 viewport heights per vertical edge |
predictSticky | 1 anticipated frame; false disables the experimental prediction |
The direct constructor also accepts scrollGetter, scrollListener,
viewportGetter, and viewportListener. Custom listeners return unsubscribe
functions. Keep custom scroll and measurement coordinates consistent.
| Method | Purpose |
|---|---|
setProjector(projector) | Attach an adapter; replacing it destroys the old adapter and bindings |
track(element, ...args) | Register through the attached projector |
update(time?) | Update positioning and projection without rendering |
requestMode(owner, mode | null) | Request 'fixed', 'absolute', or release a request |
setDefaultMode(mode) | Change the mode used when no request exists |
setPadding(value) | Change baseline overscan |
requestPadding(owner, value | null) | Add or release an overscan requirement |
setPredictSticky(frames | false) | Change sticky-entry anticipation |
refresh() | Refresh viewport geometry |
destroy() | Release trackers, adapter, and owned ruler; restore canvas styles |
Fixed requests take priority over absolute requests, then defaultMode applies.
geometry contains viewport, canvas, and clip rectangles in CSS pixels.
Listen to geometry or mode events when those change. Keep calling update()
in fixed mode too, so the canvas can detect unpinning.
ThreeProjector connects a renderer and camera to this controller. For custom
adapters, implement Projector (attach, bind, update, destroy, destroyed).
Low-level helpers projectTrackedObject, resizeThreeCanvas, and syncThreeCanvas
are also exported from portalgl/three; they do not manage your render loop.
WebGL2 fallback: one canvas
Without native WebGPU (dom.mode === 'shared-canvas'; try it with
new WebGPURenderer({ forceWebGL: true })), every view draws on one canvas: the first
child of the container, at z-index: 1 unless you style renderer.domElement.
- Overlapping views blend over each other, as WebGPU's separate canvases do. They stack
by
order(higher on top), then by their hosts' document order. Setorderwhere your hosts'z-indexdisagrees with document order. Hosts in separate shadow roots have no document order between them: each tree stacks above the trees whose hosts drew before it. - The canvas is one layer of the page: DOM can sit above or below all of its views, not
between two of them. To show views that live inside a layer with its own
z-index(a hero band, a modal), move the canvas there withdom.setContainer(layer). - From a container that can't scroll it with the page (positioned away from the
document's top-left, inside a sticky or fixed box, clipped by a box smaller than the page,
or narrower than the viewport) the canvas stays fixed to the viewport and follows the scroll
on the next frame. An
overflow: clipbox covering the whole page (to keep the canvas from lengthening it) is fine. PortalGL checks again when the page or those boxes change size, so content that loads below such a clip pins the canvas too. - Each view draws into its own target before it is composited, which costs memory per
view on this path. Scene hooks that render elsewhere must restore the previous render
target (
renderer.getRenderTarget()), notnull.
const dom = new ThreeDOM({ renderer, container: document.body })
dom.addView(sky, { scene: skyScene, camera: skyCamera, order: 1 })
dom.addView(cd, { scene: cdScene, camera: cdCamera, order: 2 })
// While the hero is on screen, paint in the hero's layer.
if (dom.mode === 'shared-canvas') dom.setContainer(hero)
Supported layouts
Use vertical page scrolling, top-pinned sticky elements, position: fixed hosts, perspective cameras,
and rectangular views. Projected objects need an untransformed parent.
Nested scroll roots, arbitrary transformed hosts, shared-canvas containers with a transformed, filtered or contained ancestor, CSS masks/border-radius clips, and automatic GPU device-loss recovery are not supported. Native WebGPU uses local view canvases; the WebGL2 fallback uses one shared canvas. Compositor scroll can still run ahead of JavaScript during main-thread stalls.
Common fixes
| Symptom | Check |
|---|---|
| Nothing renders | Renderer initialized, host has a size, and the loop calls dom.update() |
| An animation gets overwritten | Animate a child of the tracked anchor, not its managed position or scale |
| A CSS move is missed | Call tracked.refresh(); the measurement arrives asynchronously |
| A clip leaves extra space | Use clipPadding: 0 for an exact crop |
| Objects drift with a custom scroller | Ensure canvas positioning and measurements use matching scroll coordinates |
| One pipeline shows another view's scene | Create separate scene-pass and effect graphs for each registration |
| First appearance hitches | Load assets, then call await dom.prepare() before starting the loop |