# Views and 3D objects

Choose how your Three.js content follows an HTML element.



Start with the renderer and loop from [getting started](./getting-started.md).

| You want to…                                  | Use                                                      |
| --------------------------------------------- | -------------------------------------------------------- |
| Show a complete scene inside a card           | `dom.addView(element, { scene, camera })`                |
| Position a 3D object over an HTML placeholder | `dom.addScene({ scene, camera }).track(element, object)` |
| Match a plane to the full rectangle           | [Image planes](./projected-quad.md)                      |

A view changes the window onto a scene. An object binding changes an object's
position and size inside a shared scene. You can use both on one coordinator.

The [GLSync scene and views demo](https://glsync.joyco.studio/examples/scene-and-views)
combines independent views with tracked objects in a shared scene.

## Add a view [#add-a-view]

With your scene and a camera dedicated to this view:

```ts
const view = dom.addView(element, {
  scene,
  camera,
  onFrame: ({ delta }) => {
    cube.rotation.y += delta * 0.5
  },
})
```

`onFrame` runs after placement and before drawing. Register at most one callback
per scene, even when multiple views show that scene. Use `dom.update(time)` to
run it; `advance()` and `render()` alone do not invoke these callbacks.

To move or remove this view later:

```ts
view.tracked.setElement(newElement) // Follow another host.
view.tracked.refresh() // Request fresh bounds after a CSS-only position change.
view.destroy() // Remove this view; the other views keep running.
```

The scene and its assets remain yours to dispose.

## Make a 3D object follow a placeholder [#make-a-3d-object-follow-a-placeholder]

Give the placeholder a width and height, just like the card in the quickstart.
This helper adds a cube that moves with it and fills 70% of its smaller dimension.
Call it with the existing `dom`; its animation uses the existing loop.

```ts title="add-tracked-cube.ts"
import type { ThreeDOM } from 'portalgl/three'
import {
  BoxGeometry,
  ClippingGroup,
  Mesh,
  MeshNormalNodeMaterial,
  PerspectiveCamera,
  Scene,
} from 'three/webgpu'

export function addTrackedCube(dom: ThreeDOM, element: HTMLElement) {
  const scene = new Scene()
  const camera = new PerspectiveCamera(45, 1, 0.1, 100)
  camera.position.z = 4

  const geometry = new BoxGeometry()
  const material = new MeshNormalNodeMaterial()
  const cube = new Mesh(geometry, material)
  const anchor = new ClippingGroup()
  // Keep clipping programs distinct from other tracked groups on Three r184/r185.
  material.customProgramCacheKey = () => anchor.uuid
  anchor.add(cube)
  scene.add(anchor)

  const world = dom.addScene({
    scene,
    camera,
    onFrame: ({ delta }) => {
      cube.rotation.y += delta * 0.5
    },
  })
  const binding = world.track(element, anchor, { fill: 0.7, depth: 4 })

  return {
    binding,
    destroy() {
      world.destroy()
      scene.remove(anchor)
      geometry.dispose()
      material.dispose()
    },
  }
}
```

Animate the child `cube`: projection owns the anchor's position, scale, and
visibility. Keep tracked anchors directly under an untransformed scene root.
`depth` is distance from the camera; `fill` assumes a unit-size object.

For several objects that share lighting or effects, add more anchors to the same
scene and call `world.track()` for each. Give separately clipped groups their own
materials and stable program keys, as above. To allow an object to overflow its
placeholder, pass `clip: false`; an ordinary `Group` then works too.

Compare clipped and overflowing objects in the
[GLSync shared scene demo](https://glsync.joyco.studio/examples/shared-scene).

## Reveal a view through another element [#reveal-a-view-through-another-element]

When registering a view, use `clip` to crop it to another HTML rectangle:

```ts
const view = dom.addView(element, {
  scene,
  camera,
  clip: revealWindow,
  clipPadding: 0,
})
```

The view keeps its full size and camera framing as `revealWindow` moves. A
`clipPadding` of `0` crops exactly; the default `0.25` adds 25% of the clip's
size on each edge. The result always stays inside the host rectangle.

## Start rendering before a view enters [#start-rendering-before-a-view-enters]

`scrollMargin` controls how far above and below the viewport rendering starts.
Its default is `0.15` viewport heights per edge.

```ts
view.scrollMargin = 0.5 // Start half a viewport before entry.
```

Use activity events to pause extra work associated with a view:

```ts
const offActive = view.on('active', () => video.play().catch(() => {}))
const offInactive = view.on('inactive', () => video.pause())

// If you stop observing before destroying the view:
offActive()
offInactive()
```

These events follow rendering eligibility, including the margin. They do not
replay the current state when subscribed; read `view.active` if needed. Destroying
the view removes its listeners. Keep the coordinator's loop running.

Shared scenes also expose `scrollMargin` and activity events. Their `onFrame`
callbacks keep ticking offscreen so animation can bring objects back into view.

## Place custom work between tracking and rendering [#place-custom-work-between-tracking-and-rendering]

For an application that already manages animation order:

```ts
renderer.setAnimationLoop((time) => {
  dom.advance(time)
  // Read current bounds, update child objects, or set effect uniforms here.
  dom.render()
})
```

This replaces `dom.update(time)` and does not call registered `onFrame` callbacks.
Use one approach per frame.

See the [reference](./reference.md#threedom) for defaults, registration lists,
and preparation cancellation.
