This site is one 3D scene, built for a computer: a wide window and a mouse. Open dioramajs.dev on a desktop or a laptop to see it.This site is one 3D scene, built for a wide window. Make this one wider, or open dioramajs.dev on a larger screen.
A model is an effect like any other: ctx.model() loads a glTF through the shared asset cache and place() glues it to the element’s box. This guide builds a model that sits in a section, then turns it with scroll and with a pinned section.
Prepare the file
Use binary glTF (.glb) and put it where the site serves static files, for example public/models/lantern.glb. Compress the meshes before you ship them. Diorama reads the file’s extensionsUsed and loads a decoder only when the file needs one.
Extension in the file
Decoder
KHR_draco_mesh_compression
Draco, WebAssembly
EXT_meshopt_compression
Meshopt, WebAssembly
KHR_texture_basisu
Basis transcoder for KTX2
A model without compression loads no decoder at all. The decoder files come from three.js itself through import.meta.url, so your bundler emits them next to your chunks and no CDN is involved.
ctx.model(url) resolves with a copy of the model’s scene. The copy shares geometry, materials and textures with every other instance of the same file, so ten lanterns load and upload the file once. By default the copy is centred on its bounds and scaled so its largest side is 1, ready for place(…, { fit: 'contain' }).
src/effects/lantern.ts
import{
functioneffect(
setup:EffectSetup<Empty>
):Effect<Empty>(+2overloads)
Short form of defineEffect: defaults, optional options, setup. An unnamed effect takes its
registry key (the file name when a build plugin finds it).
Page transitions. 'fade' (default) multiplies the copy's alpha by u.presence. With
'custom' the effect reads u.presence or input.presence itself.
presence:'custom'},
async({
params: Readonly<
ParamsOf<ColorsIn<{ readonly src:"";}>>
>
Live resolved values. Read them in update, a read in setup is a snapshot.
params,
model:(
url: string,
options?: ModelOptions
)=>Promise<Object3D>
A glTF instance from the assets cache, clips in .animations. Starts the environment lease. Needs assets.
model,
place:<TextendsObject3D>(
object:T,
options?:PlaceOptions
)=>T
Glues an object to the box so it follows layout and pose. Disposed with the instance.
place})=>{
const
const lantern:Object3D<Object3DEventMap>
lantern=await
model:(
url: string,
options?: ModelOptions
)=>Promise<Object3D>
A glTF instance from the assets cache, clips in .animations. Starts the environment lease. Needs assets.
model(
params: Readonly<
ParamsOf<ColorsIn<{ readonly src:"";}>>
>
Live resolved values. Read them in update, a read in setup is a snapshot.
params.
src: string
src)
place:<Object3D<Object3DEventMap>>(
object: Object3D<Object3DEventMap>,
options?: PlaceOptions
)=> Object3D<Object3DEventMap>
Glues an object to the box so it follows layout and pose. Disposed with the instance.
place(
const lantern:Object3D<Object3DEventMap>
lantern,{
PlaceOptions.fit?:
|"none"
|"box"
|"contain"
|undefined
'box' (default) stretches a 1x1 object to the box, 'contain' scales it by min(width, height),
'none' keeps px units.
fit:'contain',
PlaceOptions.replace?: boolean |undefined
Use this object as the element's GL copy instead of the surface mesh.
replace:true})
},
)
fit: 'contain' scales the object by the smaller side of the box, so it keeps its proportions in any layout.
replace: true makes the model the element’s picture on the canvas. Once the model draws, the element’s own DOM hides; if WebGL is unavailable or the file fails, the DOM stays.
presence: 'custom' tells page transitions not to fade the copy through opacity. The model’s materials are shared by every instance, so their opacity cannot change for one copy.
String params rebuild the effect when they change, so a new data-dio-src loads the new file.
Put it on the page
Give the element a size and a still image of the model. The image is what visitors see before the engine loads, without WebGL and in search previews.
index.html
<img
class="lantern"
src="/models/lantern.avif"
width="800"
height="800"
data-dio="lantern"
data-dio-src="/models/lantern.glb"
/>
Live preview needs WebGPU or WebGL 2. A paper lantern model drawn over its still image in a square box; the image hides once the model draws.
This example failed to draw.
The still image is a render of the same model, so the swap does not show. Without WebGL the image stays.
<img
class="lantern"
src="/media/lantern.png"
width="800"
height="800"
data-dio="lantern"
data-dio-src="/media/lantern.glb"
/>
import{ effect }from'@dioramajs/diorama'
exportdefaulteffect(
{src:''},
{presence:'custom'},
async({ params, model, place })=>{
const lantern =awaitmodel(params.src)
place(lantern,{fit:'contain',replace:true})
},
)
start() lights lit materials with an image-based room environment, made with the first model and freed with the last. Pass render: { environment: 'none' } to start() to turn it off and add your own lights with place().
Turn it with scroll
Return an update function from setup to change the model every frame the element is visible. progress goes from 0 as the element’s top enters at the bottom of the viewport to 1 as its bottom leaves at the top.
src/effects/lantern.ts
import{
functioneffect(
setup:EffectSetup<Empty>
):Effect<Empty>(+2overloads)
Short form of defineEffect: defaults, optional options, setup. An unnamed effect takes its
registry key (the file name when a build plugin finds it).
@defaultValue ― new THREE.Euler() - that is (0, 0, 0, Euler.DEFAULT_ORDER).
rotation.
Euler.y: number
@default ― 0
y=
progress: number
Scroll progress through the viewport, like u.progress.
progress*
var Math:Math
An intrinsic object that provides basic mathematics functionality and constants.
Math.
Math.PI: number
Pi. This is the ratio of the circumference of a circle to its diameter.
PI*2
}
},
)
The effect reads no time input, so it draws only while the page scrolls. At rest it costs no frames.
Pin it to a section
For a model that stays on screen while a section scrolls past, make the section tall and keep its content in a sticky child. Put the effect on the section and read pin: it is 0 while the section’s top is below the viewport top and reaches 1 when its bottom reaches the viewport bottom.
index.html
<section
class="showcase"
data-dio="turntable"
data-dio-src="/models/lantern.glb"
>
<divclass="showcase-sticky">
<h2>Folded from one sheet</h2>
</div>
</section>
.showcase{
height:300vh;
}
.showcase-sticky{
position:sticky;
top:0;
height:100vh;
}
The section’s box is three viewports tall, so the model goes into viewport instead: a group centred on the viewport, in CSS pixels, that hides while the section is off screen.
src/effects/turntable.ts
import{
functioneffect(
setup:EffectSetup<Empty>
):Effect<Empty>(+2overloads)
Short form of defineEffect: defaults, optional options, setup. An unnamed effect takes its
registry key (the file name when a build plugin finds it).
Page transitions. 'fade' (default) multiplies the copy's alpha by u.presence. With
'custom' the effect reads u.presence or input.presence itself.
presence:'custom'},
async({
params: Readonly<
ParamsOf<ColorsIn<{ readonly src:"";}>>
>
Live resolved values. Read them in update, a read in setup is a snapshot.
params,
model:(
url: string,
options?: ModelOptions
)=>Promise<Object3D>
A glTF instance from the assets cache, clips in .animations. Starts the environment lease. Needs assets.
model,
viewport: Group<Object3DEventMap>
Group pinned to the viewport (centre 0,0, world px). It does not scroll with the element,
ignores pose and hides while the layer is off screen. Use place(g, { fit: 'none' }) to
follow the box instead.
viewport,
app: EffectApp
Kernel scope of the instance: services, listeners and systems that die with it.
app})=>{
const
const lantern:Object3D<Object3DEventMap>
lantern=await
model:(
url: string,
options?: ModelOptions
)=>Promise<Object3D>
A glTF instance from the assets cache, clips in .animations. Starts the environment lease. Needs assets.
model(
params: Readonly<
ParamsOf<ColorsIn<{ readonly src:"";}>>
>
Live resolved values. Read them in update, a read in setup is a snapshot.
params.
src: string
src)
viewport: Group<Object3DEventMap>
Group pinned to the viewport (centre 0,0, world px). It does not scroll with the element,
ignores pose and hides while the layer is off screen. Use place(g, { fit: 'none' }) to
follow the box instead.
viewport.
Object3D<Object3DEventMap>.add(
...object: Object3D[]
): Group<Object3DEventMap>
Adds another
Object3D
as child of this
Object3D
.
@remarks ― An arbitrary number of objects may be added
Any current parent on an object passed in here will be removed, since an Object3D can have at most one parent.
@see ― attach
@see ― THREE.Group Group for info on manually grouping objects.
@param ― object
add(
const lantern:Object3D<Object3DEventMap>
lantern)
return({
pin: number
Pin progress, like u.pin.
pin})=>{
const
const size:number
size=
var Math:Math
An intrinsic object that provides basic mathematics functionality and constants.
Math.
Math.min(...values: number[]): number
Returns the smaller of a set of supplied numeric expressions.
@param ― values Numeric expressions to be evaluated.
min(
app: EffectApp
Kernel scope of the instance: services, listeners and systems that die with it.
app.
stage: StageApi
The canvas and the viewport.
stage.
StageApi.width: ReadonlySignal<number>
Viewport size in CSS px, excluding scrollbars.
width.
ReadonlySignal<number>.value: number
Current value. Reading it inside effect or computed tracks it.
value,
app: EffectApp
Kernel scope of the instance: services, listeners and systems that die with it.
app.
stage: StageApi
The canvas and the viewport.
stage.
StageApi.height: ReadonlySignal<number>
Viewport height in CSS px, excluding scrollbars.
height.
ReadonlySignal<number>.value: number
Current value. Reading it inside effect or computed tracks it.
@defaultValue ― new THREE.Euler() - that is (0, 0, 0, Euler.DEFAULT_ORDER).
rotation.
Euler.y: number
@default ― 0
y=
pin: number
Pin progress, like u.pin.
pin*
var Math:Math
An intrinsic object that provides basic mathematics functionality and constants.
Math.
Math.PI: number
Pi. This is the ratio of the circumference of a circle to its diameter.
PI*2
const lantern:Object3D<Object3DEventMap>
lantern.
Object3D<Object3DEventMap>.position: Vector3
Object's local position.
@defaultValue ― new THREE.Vector3() - that is (0, 0, 0).
position.
Vector3.y: number
@default ― 0
y=(0.5-
pin: number
Pin progress, like u.pin.
pin)*80
}
},
)
Folded from one sheet
Live preview needs WebGPU or WebGL 2. A section three viewports tall with a sticky heading: the lantern stays in the middle of the viewport and turns once while the section scrolls through.
This example failed to draw.
Scroll through the section: the lantern turns once and sinks a little on the way.
With GSAP, pin the section with ScrollTrigger instead of CSS. Pass gsap and ScrollTrigger to start(), and effects inside a pinned trigger get its scrubbed progress as pin without more code. GSAP and Lenis covers the setup.
Play its animation
The clips of the file are on the returned object’s animations. Drive a three.js AnimationMixer from the update function and ask for a frame every time the model is visible.
src/effects/lantern.ts
import{
functioneffect(
setup:EffectSetup<Empty>
):Effect<Empty>(+2overloads)
Short form of defineEffect: defaults, optional options, setup. An unnamed effect takes its
registry key (the file name when a build plugin finds it).
AnimationMixer is a player for animations on a particular object in
the scene. When multiple objects in the scene are animated independently,
one AnimationMixer may be used for each object.
Page transitions. 'fade' (default) multiplies the copy's alpha by u.presence. With
'custom' the effect reads u.presence or input.presence itself.
presence:'custom',
animate?:
| AnimatePolicy<ColorsIn<{ readonly src:"";}>>
|undefined
Defaults to the update's answer when it returns a boolean, else to what the effect reads:
time animates every visible frame, hoverTime while hovered or hover decays, neither
means 'input'.
animate:'visible'},
async({
params: Readonly<
ParamsOf<ColorsIn<{ readonly src:"";}>>
>
Live resolved values. Read them in update, a read in setup is a snapshot.
params,
model:(
url: string,
options?: ModelOptions
)=>Promise<Object3D>
A glTF instance from the assets cache, clips in .animations. Starts the environment lease. Needs assets.
model,
place:<TextendsObject3D>(
object:T,
options?:PlaceOptions
)=>T
Glues an object to the box so it follows layout and pose. Disposed with the instance.
place})=>{
const
const lantern:Object3D<Object3DEventMap>
lantern=await
model:(
url: string,
options?: ModelOptions
)=>Promise<Object3D>
A glTF instance from the assets cache, clips in .animations. Starts the environment lease. Needs assets.
model(
params: Readonly<
ParamsOf<ColorsIn<{ readonly src:"";}>>
>
Live resolved values. Read them in update, a read in setup is a snapshot.
params.
src: string
src)
place:<Object3D<Object3DEventMap>>(
object: Object3D<Object3DEventMap>,
options?: PlaceOptions
)=> Object3D<Object3DEventMap>
Glues an object to the box so it follows layout and pose. Disposed with the instance.
place(
const lantern:Object3D<Object3DEventMap>
lantern,{
PlaceOptions.fit?:
|"none"
|"box"
|"contain"
|undefined
'box' (default) stretches a 1x1 object to the box, 'contain' scales it by min(width, height),
'none' keeps px units.
fit:'contain',
PlaceOptions.replace?: boolean |undefined
Use this object as the element's GL copy instead of the surface mesh.
If an action fitting the clip and root parameters doesn't yet exist, it
will be created by this method. Calling this method several times with the
same clip and root parameters always returns the same action.
@param ― clip - An animation clip or alternatively the name of the animation clip.
@param ― optionalRoot - An alternative root object.
Advances the global mixer time and updates the animation.
This is usually done in the render loop by passing the delta
time from
Clock
or
Timer
.
@param ― deltaTime - The delta time in seconds.
@return ― A reference to this animation mixer.
update(
frame: FrameTime
frame.
FrameTime.delta: number
Seconds since the last frame, scaled by timeScale and capped by maxDelta.
delta)
}
},
)
animate: 'visible' draws every frame while the element is on screen, and none once it scrolls away. Under reduced motion the policy asks for no frames, and the check keeps the clip still on the frames that do run.
Preload it
Models load when the element nears the viewport. To have one ready when a visitor follows a link, name it in data-dio-preload: hovering for 65 ms, focusing or touching the link puts the file in the cache.
<a
href="/lantern"
data-dio-preload="/models/lantern.glb"
>The lantern</a>
Loading and preloading has the rest: preloading from router code and a progress bar for the first screen.
Decoders under a content security policy
Draco, Meshopt and KTX2 run in blob: workers and WebAssembly. Under a content security policy, allow both, or the load fails with ASSET_DECODER.
To serve the decoders from your own folder, pass assets() with decoders in plugins. Its options merge with the cache start() already adds.
src/main.ts
import{
const assets:Plugin<
"assets",
AssetsOptions,
AssetsApi,
never
>
app.assets. One cache with leases for media and models, a priority queue, preloading of
the next page and the progress wave of a preloader.
assets,
functionstart(options?:StartOptions):App
Starts Diorama on the page and returns the app at once. It finishes starting in the
background. A second call returns the same app, so a re-run module doesn't make another.
import { start } from '@dioramajs/diorama'
export const app = start()
start}from'@dioramajs/diorama'
exportconst
const app:App
app=
functionstart(options?:StartOptions):App
Starts Diorama on the page and returns the app at once. It finishes starting in the
background. A second call returns the same app, so a re-run module doesn't make another.
import { start } from '@dioramajs/diorama'
export const app = start()
start({
StartOptions.plugins?:
| readonly PluginEntry[]
|undefined
Extra plugins, your own or official ones with more options.
plugins:[
functionassets(
options?:Partial<AssetsOptions>|undefined
):Plugin<"assets",AssetsOptions,AssetsApi,never>
app.assets. One cache with leases for media and models, a priority queue, preloading of
the next page and the progress wave of a preloader.
assets({
decoders?: Partial<DecoderOptions>|undefined
Where the Draco, KTX2 and Meshopt decoders come from.
decoders:{
draco?:
| string
|false
|{ readonly js: string; readonly wasm: string;}
|undefined
A directory or { js, wasm }, false refuses. Defaults to three's glTF-only build next to DRACOLoader.
draco:'/draco/',
ktx2?: string |false|undefined
A directory, false refuses. Defaults to three's Basis transcoder next to KTX2Loader.
ktx2:'/basis/'}}),
],
})
draco: false or ktx2: false refuses that kind of file with ASSET_DECODER instead of loading a decoder.