Primitives

ModelViewer

An interactive three.js view of a GLB or glTF model

Renders a .glb or .gltf model. three.js is fetched only when a viewer comes near the viewport, so pages without one never load it. Compressed models (Draco, meshopt, KTX2) are not supported.

Basic

Drag to orbit and scroll to zoom. The camera frames the model from its bounds.

basic
---
import ModelViewer from '@alfadormx/blocks/primitives/ModelViewer.astro';
---

<ModelViewer src="/models/avocado.glb" label="An avocado cut in half" />

glTF with external resources

A .gltf loads its .bin and textures relative to src.

gltf
---
import ModelViewer from '@alfadormx/blocks/primitives/ModelViewer.astro';
---

<ModelViewer src="/models/water-bottle/WaterBottle.gltf" label="A water bottle" />

Camera framing

Set cameraPosition, cameraTarget and fov to frame the model deliberately. Any value left out is still derived from the model’s bounds.

camera
---
import ModelViewer from '@alfadormx/blocks/primitives/ModelViewer.astro';
---

<ModelViewer
  src="/models/avocado.glb"
  label="An avocado seen from above"
  cameraPosition={[0, 0.12, 0.02]}
  fov={30}
  class="rounded-lg bg-surface"
/>

Autorotate

autoRotate spins the model, pausing while the user drags it. It is ignored when the visitor prefers reduced motion.

autorotate
---
import ModelViewer from '@alfadormx/blocks/primitives/ModelViewer.astro';
---

<ModelViewer src="/models/avocado.glb" label="A rotating avocado" autoRotate />

Lighting and shadow

Pick a lighting preset and tune exposure. Add shadow to ground the model.

lighting
---
import ModelViewer from '@alfadormx/blocks/primitives/ModelViewer.astro';

const presets = ['studio', 'neutral', 'soft'] as const;
---

<div class="grid gap-4 md:grid-cols-3">
  {presets.map((preset) => (
    <ModelViewer
      src="/models/water-bottle/WaterBottle.gltf"
      label={`A water bottle under ${preset} lighting`}
      lighting={preset}
      shadow
      height="300px"
    />
  ))}
</div>

Environment

Set environment.src to a .hdr file to light and reflect the model from a real studio instead of the generated one. environment.rotation turns it, in degrees, to place the highlights.

Pair an HDR with lighting="neutral": the preset still sets the key light, shadow and environment intensity, but its blur only applies to the generated environment. Tune overall brightness with exposure. The HDR is never drawn behind the model, so set a background with class. If the file fails to load, the viewer falls back to the generated environment.

environment
---
import ModelViewer from '@alfadormx/blocks/primitives/ModelViewer.astro';

const hdr = '/hdr/studio_small_08_1k.hdr';
---

<div class="grid gap-4 md:grid-cols-2">
  <ModelViewer
    src="/models/ring.glb"
    label="A ring lit by a studio HDR"
    lighting="neutral"
    environment={{ src: hdr }}
    height="300px"
  />
  <ModelViewer
    src="/models/ring.glb"
    label="A ring lit by the same studio HDR turned half a turn"
    lighting="neutral"
    environment={{ src: hdr, rotation: 180 }}
    height="300px"
  />
</div>

environment.autoRotate spins the environment so reflections move across the piece while the model and camera stay still; environment.autoRotateSpeed uses the same scale as autoRotateSpeed. It keeps turning while the user drags and is ignored when the visitor prefers reduced motion.

environment-spin
---
import ModelViewer from '@alfadormx/blocks/primitives/ModelViewer.astro';

const hdr = '/hdr/studio_small_08_1k.hdr';
---

<ModelViewer
  src="/models/ring.glb"
  label="A ring with reflections moving across it"
  lighting="neutral"
  environment={{ src: hdr, autoRotate: true }}
/>

Bloom

Set bloom to make the highlights on stones glow. Only diamond-like materials (index of refraction 2 or more) glow; metal and everything else stay as they are. It draws the scene a second time and adds post-processing passes on every frame while the view moves, so use it where the sparkle matters.

Only stone highlights brighter than white, before tone mapping, glow. Pair it with lighting="neutral" and an HDR environment; the dimmer presets leave little bright enough to glow. exposure brightens the glow with the rest of the image but does not change which highlights glow. The canvas stays transparent. The glow does not animate on its own; glints move as the camera or environment turns.

bloom
---
import ModelViewer from '@alfadormx/blocks/primitives/ModelViewer.astro';

const hdr = '/hdr/studio_small_08_1k.hdr';
---

<div class="grid gap-4 md:grid-cols-2">
  <ModelViewer
    src="/models/ring-pave.glb"
    label="A pavé ring without bloom"
    lighting="neutral"
    environment={{ src: hdr }}
    shadow
    height="300px"
  />
  <ModelViewer
    src="/models/ring-pave.glb"
    label="A pavé ring with glowing highlights"
    lighting="neutral"
    environment={{ src: hdr }}
    shadow
    bloom
    height="300px"
  />
</div>

Configurator

Pair the viewer with selection blocks such as ToggleGroup and TextArea to build a product configurator. Pick a style to load another model file, a band finish to recolour the ring, and a carat to switch which stone is shown. Typing an engraving moves the camera to the band once.

configurator
---
import ModelViewer from '@alfadormx/blocks/primitives/ModelViewer.astro';
import TextArea from '@alfadormx/blocks/primitives/TextArea.astro';
import ToggleGroup from '@alfadormx/blocks/primitives/ToggleGroup.astro';
import type { ModelViewerProps } from '@alfadormx/blocks/types/modelviewer';

const ringSelections: ModelViewerProps['selections'] = {
  'modelviewer-doc-model': {
    options: {
      classic: [{ type: 'model', src: '/models/ring.glb' }],
      bold: [{ type: 'model', src: '/models/ring-alt.glb' }],
    },
  },
  'modelviewer-doc-band': {
    options: {
      yellow: [{ type: 'material', material: 'Band', color: '#e6b422', roughness: 0.3 }],
      white: [{ type: 'material', material: 'Band', color: '#e5e4e2', roughness: 0.2 }],
      rose: [{ type: 'material', part: 'Band', use: 'RoseGold' }],
    },
  },
  'modelviewer-doc-carat': {
    options: {
      small: [{ type: 'visible', parts: ['Stone_Small'] }],
      medium: [{ type: 'visible', parts: ['Stone_Medium'] }],
      large: [{ type: 'visible', parts: ['Stone_Large'] }],
    },
  },
  'modelviewer-doc-engraving': { camera: 'band' },
};
const ringCameraPresets: ModelViewerProps['cameraPresets'] = {
  band: { position: [0, -0.9, 2.4], target: [0, -0.6, 0], fov: 35 },
};
const styleOptions = [
  { code: 'classic', label: 'Classic' },
  { code: 'bold', label: 'Bold' },
];
const bandOptions = [
  { code: 'yellow', label: 'Yellow gold' },
  { code: 'white', label: 'White gold' },
  { code: 'rose', label: 'Rose gold' },
];
const caratOptions = [
  { code: 'small', label: 'Small' },
  { code: 'medium', label: 'Medium', selected: true },
  { code: 'large', label: 'Large' },
];
---

<div class="grid gap-6 md:grid-cols-[2fr_1fr]">
  <ModelViewer
    src="/models/ring.glb"
    label="A configurable ring"
    selections={ringSelections}
    cameraPresets={ringCameraPresets}
    class="rounded-lg bg-surface"
  />
  <div class="flex flex-col gap-4">
    <ToggleGroup group="modelviewer-doc-model" label="Style" options={styleOptions} />
    <ToggleGroup group="modelviewer-doc-band" label="Band" options={bandOptions} />
    <ToggleGroup group="modelviewer-doc-carat" label="Carat" options={caratOptions} />
    <TextArea group="modelviewer-doc-engraving" label="Engraving" maxLength={20} rows={2} />
    <div class="flex flex-wrap gap-2">
      <div data-selection-group="modelviewer-doc-band" data-selection-mode="single">
        <button type="button" data-selection-clear class="px-3 py-1 border border-border rounded">
          Reset band
        </button>
      </div>
      <div data-selection-group="modelviewer-doc-carat" data-selection-mode="single">
        <button type="button" data-selection-clear class="px-3 py-1 border border-border rounded">
          Reset carat
        </button>
      </div>
    </div>
  </div>
</div>

<script>
  import { publish } from '@alfadormx/blocks/selection';

  function initReset(): void {
    document
      .querySelectorAll<HTMLButtonElement>(
        '[data-doc-section="configurator"] [data-selection-clear]'
      )
      // onclick, not addEventListener: re-running initReset replaces the handler instead of stacking it.
      .forEach((button) => (button.onclick = () => publish(button, [])));
  }

  document.addEventListener('astro:after-swap', initReset);
  initReset();
</script>

Selections

selections is keyed by selection group name, then by option code, and maps each code to a list of ModelViewerMutations applied while that code is selected. Every change starts again from the model as loaded and applies the groups in declaration order, so when two groups set the same property the later one wins. Clearing a group’s selection reverts what it changed. Group keys must not be integer-like, because JavaScript would reorder them. A group on a text selection only supports camera, since its codes are free input. Names match the glTF file as authored, so check them in the file rather than in three.js.

A material edit changes every mesh that uses the named glTF material. Colours are #rgb or #rrggbb in sRGB; metalness and roughness run from 0 to 1.

Some exporters, such as KeyShot, write one material per mesh, named Gold_1, Gold_2 and so on. When a model loads, materials whose names differ only by a trailing _<n> and whose glTF definitions are identical are merged into one. A material name also matches its family, the name without that suffix, so material: 'Gold' reaches every Gold_<n> mesh, and each original name still works.

{
  "type": "material",
  "material": "Band",
  "color": "#e5e4e2",
  "metalness": 1,
  "roughness": 0.2
}

A material swap with use assigns another material from the same file to a named part, such as a variant that no mesh uses by default.

{
  "type": "material",
  "part": "Band",
  "use": "RoseGold"
}

visible shows the listed glTF nodes and their children. While a group has a selection, every part its options list is hidden first, so exactly the selected option’s parts are shown; parts the group never lists are left alone.

{
  "type": "visible",
  "parts": ["Stone_Medium"]
}

model replaces the file. The last selected model mutation wins, falling back to src. The current model stays on screen until the new one has loaded, the camera keeps its position, and the other groups are applied to the new model. If the file fails to load, the current model stays. The files should share part and material names.

{
  "type": "model",
  "src": "/models/ring-alt.glb"
}

Camera presets

cameraPresets names camera positions as a position and target in model units, plus an optional fov. A group’s camera names the preset to move to when that group changes after a different group did, so typing more into the same field never fights the visitor’s orbiting. The camera eases over about 600 ms, or jumps when the visitor prefers reduced motion, and dragging stops the move where it is. Applying a preset turns off autoRotate.

Development warnings

Malformed configuration throws at build time. Problems that depend on the page or the model file log a single [ModelViewer] warning each in development and nothing in production: a group that is not declared on the page, options on a text group, a material or part missing from the model, and a model file that fails to load. The viewer keeps rendering either way. This example names things that do not exist; open the console and pick the options.

warnings
---
import ModelViewer from '@alfadormx/blocks/primitives/ModelViewer.astro';
import ToggleGroup from '@alfadormx/blocks/primitives/ToggleGroup.astro';
---

<div class="grid gap-6 md:grid-cols-[2fr_1fr]">
  <ModelViewer
    src="/models/ring.glb"
    label="A ring configured with names that do not exist"
    height="300px"
    selections={{
      'modelviewer-doc-undeclared': { options: {} },
      'modelviewer-doc-warnings': {
        options: {
          missing: [
            { type: 'material', material: 'Platinum', color: '#cccccc' },
            { type: 'visible', parts: ['Stone_Huge'] },
          ],
          broken: [{ type: 'model', src: '/models/missing.glb' }],
        },
      },
    }}
    class="rounded-lg bg-surface"
  />
  <ToggleGroup
    group="modelviewer-doc-warnings"
    label="Broken options"
    options={[
      { code: 'missing', label: 'Missing names' },
      { code: 'broken', label: 'Missing file' },
    ]}
  />
</div>

Failure message

When WebGL is unavailable or the model cannot be loaded, the viewer shows the matching messages text instead of a blank area. This example points at a missing file.

error
---
import ModelViewer from '@alfadormx/blocks/primitives/ModelViewer.astro';
---

<ModelViewer
  src="/models/missing.glb"
  label="Missing model"
  height="200px"
  messages={{ loadFailed: 'This product preview is unavailable right now.' }}
/>

API Reference

PropTypeDefaultDescription
srcstring—URL of the .glb or .gltf model; a .gltf loads its .bin and textures relative to this URL.
labelstring—Accessible name of the rendered model, used as the canvas aria-label.
orbitbooleantrueLets the user orbit the model by dragging (default: true).
zoombooleantrueLets the user zoom with the wheel or a pinch (default: true).
autoRotatebooleanfalseSpins the model continuously; ignored under prefers-reduced-motion (default: false).
autoRotateSpeednumber2Autorotate speed; 2 is one turn every 30 seconds (default: 2).
cameraPositionVec3—Camera position in model units; auto-framed from the model's bounds when omitted.
cameraTargetVec3—Point the camera looks at and orbits around; the model's centre when omitted.
fovnumber45Vertical field of view in degrees, between 0 and 180 exclusive (default: 45).
lighting'studio' | 'neutral' | 'soft''studio'Lighting preset: sets the key light, shadow strength and environment intensity; the environment is generated unless `environment` is set (default: 'studio').
exposurenumber1Tone-mapping exposure; higher is brighter (default: 1).
shadowbooleanfalseCasts a soft shadow onto a ground plane under the model (default: false).
bloombooleanfalseMakes the highlights on diamond-like stones glow; draws the scene twice while the view moves. See "Bloom" above (default: false).
environmentModelViewerEnvironment—HDR environment that replaces the generated studio for reflections and lighting; the canvas stays transparent. See "Environment" above.
messages{ webglUnavailable?: string; loadFailed?: string }{}Messages shown when WebGL is unavailable or the model fails to load (default: English text for each).
heightstring—CSS height, applied inline so it beats any class; when omitted the viewer is 400px tall through a class that `class` can override, breakpoint prefixes included.
widthstring'100%'CSS width of the viewer (default: '100%').
selectionsRecord<string, ModelViewerSelectionGroup>{}Scene changes keyed by selection group, then option code; see "Selections" above (default: {}).
cameraPresetsRecord<string, ModelViewerCameraPreset>{}Named camera positions that selection groups can move to; see "Camera presets" above (default: {}).
classstring''Additional classes on the viewer root; the canvas is transparent, so set a background here.