---
title: Embed the viewer
summary: Create the client, the ModelManager, the ObjectStateManager and a Viewer3d, initialise it, put it on the page and choose its settings.
order: 10
languages: [javascript]
terms: [api-token, object-state-manager, model-manager, viewer]
see-also: [tutorials/javascript-viewer/load-a-model, how-to/install/javascript, how-to/viewer3d/embed-the-viewer, reference/viewer3d/key-bindings]
---

# Embed the viewer

The first lesson ends with an empty viewer on the page. Empty, because loading a model is the next lesson; but everything the later lessons need is already there. The rounds of this lesson start from nothing: your code creates every object itself, in the order of the [four objects](index.md#the-four-objects).

## From a token to a viewer

Five steps, each one line:

- `new BimWorksClientFactory(BIM_WORKS_ADDRESS)` is made once per instance you talk to; `createClientWithApiToken` logs in and returns a client. Both are asynchronous where the network is involved, so the code awaits them. Keep the client for the life of the page; call `client.close()` when you leave.
- `new ModelManager(client)` and `new ObjectStateManager(modelManager)` are plain constructors. The ObjectStateManager takes a settings object as second argument; `{multiSelect: true}`, Shift-click to extend the selection, is the default.
- `new Viewer3d(objectStateManager, loadProgressHandler, settings)`: the second argument reports load progress (lesson two), the third is the viewer settings. Both may be left out or `null`.
- `await viewer.initializeViewer()` creates the WebGL context and starts the render loop. Do not call anything else on the viewer before it resolves, and call it once.
- `viewer.container` is the element the viewer draws in. Append it wherever you want; the viewer follows the size of that element.

```lesson {#lesson-1}
goal: Put an initialised 3D viewer on the page.
language: javascript
setup: none
check: viewer
starter: |
  // A factory per BIM.works instance, a client per login
  const factory = new BimWorksClientFactory(BIM_WORKS_ADDRESS);
  const client = await factory.createClientWithApiToken(BIM_WORKS_API_TOKEN);

  // Now the ModelManager, the ObjectStateManager and the Viewer3d
hints: |
  - `new ModelManager(client)` and `new ObjectStateManager(modelManager)` come first: the viewer needs the ObjectStateManager.
  - `new Viewer3d(objectStateManager)` creates the viewer, and nothing is drawn until `await viewer.initializeViewer()` has resolved.
  - The viewer draws in `viewer.container`: append it to `document.body`.
solution: |
  const factory = new BimWorksClientFactory(BIM_WORKS_ADDRESS);
  const client = await factory.createClientWithApiToken(BIM_WORKS_API_TOKEN);
  const modelManager = new ModelManager(client);
  const objectStateManager = new ObjectStateManager(modelManager);
  const viewer = new Viewer3d(objectStateManager, null, {});
  await viewer.initializeViewer();
  document.body.appendChild(viewer.container);
accept: |
  - const client = await new BimWorksClientFactory(BIM_WORKS_ADDRESS).createClientWithApiToken(BIM_WORKS_API_TOKEN);
    const viewer = new Viewer3d(new ObjectStateManager(new ModelManager(client)));
    await viewer.initializeViewer();
    document.body.append(viewer.container);
```

Once the round has run, the viewer above is empty: there is nothing to draw yet. It is alive all the same. The default navigation mode is orbit: drag with the left button to orbit, with the middle button or Shift and the left button to pan, scroll to zoom. Ctrl and the left button places a section plane, Alt and the left button looks around, and the keyboard moves the camera (`W`/`S`/`A`/`D`, `Q`/`Z` up and down, the arrow keys). `F` fits the view to the selection, `H` hides the selected objects, `C` and `D` colour them, Space toggles the turntable animation. All bindings are listed in [[page:reference/viewer3d/key-bindings]] and can be replaced through the `navigationModes` setting.

## Settings worth knowing

The third constructor argument accepts a `Viewer3dSettings` object. Three settings matter from the start:

```javascript {#settings}
const viewer = new Viewer3d(objectStateManager, null, {
	// Off by default; on, decoding and culling leave the main thread. Some bundlers
	// need configuration before workers load, which is why the default is off.
	technologyAllowed: {webGl2: true, webWorker: true},
	// Keep geometry in the browser's IndexedDB so a second load of the same version is fast
	cacheGeometry: true,
	// Show the built-in loading indicator (styled through the .viewer3d.loader class)
	showLoader: true
});
```

Web worker rendering is controlled by `technologyAllowed.webWorker` and nothing else. Workers run on any page; only sharing memory with them (`technologyAllowed.sharedArrayBuffer`) needs a page that is cross-origin isolated, and without it the viewer transfers buffers to the workers instead, when `technologyAllowed.transferable` allows that. The lessons on this page are the exception: their runtime switches workers off whenever the page is not cross-origin isolated, whatever you pass. The full settings type is on the [[page:reference/viewer3d|Viewer3d reference]].

Some things are switched after the viewer is initialised rather than in the settings. The reference grid is one: `viewer.setGridEnabled(true)` lays an infinite metric grid on the ground plane, which gives an empty scene something to orbit around and a model something to stand on.

```lesson {#lesson-2}
goal: Keep the geometry of loaded models in the browser's cache, and show the reference grid in the empty viewer.
language: javascript
setup: none
check: viewer
starter: |
  const factory = new BimWorksClientFactory(BIM_WORKS_ADDRESS);
  const client = await factory.createClientWithApiToken(BIM_WORKS_API_TOKEN);
  const modelManager = new ModelManager(client);
  const objectStateManager = new ObjectStateManager(modelManager);
  const viewer = new Viewer3d(objectStateManager, null, {});
  await viewer.initializeViewer();
  document.body.appendChild(viewer.container);
hints: |
  - The cache is a setting: it goes in the object that is the third argument of `new Viewer3d`.
  - The setting is `cacheGeometry`.
  - The grid is switched on after `initializeViewer()`: `viewer.setGridEnabled(true)`.
solution: |
  const factory = new BimWorksClientFactory(BIM_WORKS_ADDRESS);
  const client = await factory.createClientWithApiToken(BIM_WORKS_API_TOKEN);
  const modelManager = new ModelManager(client);
  const objectStateManager = new ObjectStateManager(modelManager);
  const viewer = new Viewer3d(objectStateManager, null, {cacheGeometry: true});
  await viewer.initializeViewer();
  document.body.appendChild(viewer.container);
  viewer.setGridEnabled(true);
accept: |
  - const factory = new BimWorksClientFactory(BIM_WORKS_ADDRESS);
    const client = await factory.createClientWithApiToken(BIM_WORKS_API_TOKEN);
    const modelManager = new ModelManager(client);
    const objectStateManager = new ObjectStateManager(modelManager);
    const viewer = new Viewer3d(objectStateManager, null, {
    	technologyAllowed: {webGl2: true, webWorker: true},
    	cacheGeometry: true,
    	showLoader: true
    });
    await viewer.initializeViewer();
    viewer.setGridEnabled(true);
    document.body.appendChild(viewer.container);
```

Orbit and zoom over the grid: its spacing follows the zoom in steps of ten, from 10 cm to 10 m and beyond.

## Your own page

In the rounds the page around the code was given. On a page of your own the packages are imports, the client comes from a token your backend issues rather than from the API token ([[page:how-to/viewer3d/show-your-users-models]]), and the page gives the viewer its size: the container is a block element with the class `viewer3d` and no intrinsic size. In the CSS tab below the body is a column flexbox that fills the window and `.viewer3d` takes the remaining space with `flex: 1`. Without a rule like that the viewer is zero pixels high and you see nothing. The viewer resizes itself when its container changes size, so a responsive layout needs no code.

```example
name: viewer-embed
code: javascript/viewer-embed.js
run: none
css: javascript/viewer-embed.css
html: javascript/viewer-embed.html
notes: |
  The Code tab is the program of the first two rounds. The HTML tab is the same program as a page of your own: the packages are imported, and the CSS sizes the viewer. With a bundler the imports resolve to the npm packages; without one an import map points them at the single-file builds ([[page:how-to/install/javascript]]).
highlight: 8-16
```

## Cleaning up

A viewer holds GPU memory and a render loop. When your page removes it, call `viewer.destroy()`; when it is merely hidden, `viewer.stop()` and later `viewer.start()` save the work of rendering an invisible canvas. The rounds do the same between two runs: the viewer your code created is destroyed and its client closed before the next run starts.

## You can now

- Create a client from an API token and the two managers a viewer needs.
- Construct and initialise a `Viewer3d` and place it in your layout.
- Pass the viewer its settings, and switch on the reference grid.
- Navigate a scene with mouse and keyboard.

Next: [Load a model](load-a-model.md).
