# Tracking and custom rendering

Read DOM bounds without a renderer, or fit PortalGL into your existing render loop.



Use the lower-level API when you need measured rectangles or already control how
your scene renders. For ordinary views and post-processing, start with
[ThreeDOM](./getting-started.md).

## Watch an element's bounds [#watch-an-elements-bounds]

This standalone helper needs only PortalGL. Its callback receives
viewport coordinates in CSS pixels, including updates caused by scrolling.

```ts title="watch-bounds.ts"
import { TrackedElement, TrackingContext, type ViewportRect } from 'portalgl'

export function watchBounds(
  element: HTMLElement,
  onBounds: (rect: ViewportRect | null) => void
) {
  const source = new TrackingContext()
  const tracked = new TrackedElement({ source, element })
  const off = tracked.on('bounds', onBounds)

  return {
    tracked,
    destroy() {
      off()
      source.destroy() // Also releases this source's trackers.
    },
  }
}
```

```ts
import { watchBounds } from './watch-bounds'

const element = document.querySelector<HTMLElement>('#card')!
const watcher = watchBounds(element, (rect) => {
  if (rect) console.log(rect.top, rect.left, rect.width, rect.height)
})

// Call watcher.destroy() when the element's owner unmounts.
```

`tracked.rect` starts as `null` until measurement arrives. Use
`tracked.refresh()` after moving an element through CSS without resizing it, or
`tracked.setElement(nextElement)` to follow another element.

For sticky elements, `tracked.state.pinned` tells you whether they are pinned.
`state.active` means pinned for sticky elements and visible for ordinary elements;
it is not a general visibility test.

`position: fixed` hosts (or hosts inside a fixed ancestor) keep their viewport
rectangle while the page scrolls, and pin a shared canvas while visible. A fixed
host inside a `transform`, `filter`, or `contain` ancestor scrolls with the page,
as CSS lays it out.

Measurements and cleanup are automatic. Destroying the source also destroys its
trackers; other PortalGL controllers keep working.

## Use your existing renderer [#use-your-existing-renderer]

This helper accepts your renderer, perspective camera, and a scene object. It
works with classic `WebGLRenderer` as well as `WebGPURenderer`.

```ts title="track-object.ts"
import type { Object3D, PerspectiveCamera } from 'three'
import { DynamicCanvas, ThreeProjector, type ThreeRenderer } from 'portalgl/three'

export function trackObject(
  renderer: ThreeRenderer,
  camera: PerspectiveCamera,
  element: HTMLElement,
  object: Object3D
) {
  const canvas = new DynamicCanvas<ThreeProjector>({ padding: 0.25 })
  canvas.setProjector(new ThreeProjector({ renderer, camera }))
  const binding = canvas.track(element, object, { fill: 0.7, clip: false })

  return {
    binding,
    update(time: number) {
      canvas.update(time)
    },
    destroy() {
      canvas.destroy()
    },
  }
}
```

Keep the object directly under an untransformed scene root. Attach the renderer's
canvas to a container at document origin and give it `width: 100%; display: block;
pointer-events: none`. For example, with `body { margin: 0 }`:

```ts
import { trackObject } from './track-object'

Object.assign(renderer.domElement.style, {
  width: '100%',
  display: 'block',
  pointerEvents: 'none',
})
document.body.append(renderer.domElement)
const tracking = trackObject(renderer, camera, element, object)

renderer.setAnimationLoop((time) => {
  // Update camera controls here, before projection.
  tracking.update(time)
  renderer.render(scene, camera)
})

// On teardown: stop the loop, destroy tracking, then release your own resources.
// renderer.setAnimationLoop(null)
// tracking.destroy()
// renderer.domElement.remove()
```

`canvas.update()` positions the canvas, sizes the renderer and camera, and
projects its objects. It does not render or start a loop. Animate children of the
tracked object so projection does not overwrite your animation.

The example allows overflow with `clip: false`. For clipping with
`WebGPURenderer`, track a `ClippingGroup` as shown in the
[3D object recipe](./dom-track.md#make-a-3d-object-follow-a-placeholder).
Initialize that renderer with `await renderer.init()` before connecting it.

Use [`DynamicCanvas`](./reference.md#dynamiccanvas) directly for custom scroll
sources or a renderer adapter that implements PortalGL's `Projector` interface.
