@dandre3000/three-canvas-sandbox
v0.2.0
Published
Three.js OffscreenCanvas renderer in a worker sandbox.
Maintainers
Readme
@dandre3000/three-canvas-sandbox
Three.js OffscreenCanvas renderer in a worker sandbox.
Install
npm i @dandre3000/three-canvas-sandbox
Usage
import { ThreeCanvasSandbox } from '@dandre3000/three-canvas-sandbox'
const canvasSandbox = new ThreeCanvasSandbox
document.body.appendChild(canvasSandbox.canvasContainer)
const createScene = () => {
/** @type {import('@dandre3000/three-canvas-sandbox').ThreeCanvasSandboxContext} */
const { renderer, three } = (globalThis)
const { x, y } = renderer.getSize(new three.Vector2)
const scene = new three.Scene()
const camera = new three.PerspectiveCamera(75, x / y, 0.1, 1000)
const geometry = new three.BoxGeometry(1, 1, 1)
const material = new three.MeshBasicMaterial({ color: 0x00ff00 })
const cube = new three.Mesh(geometry, material)
scene.add(cube)
camera.position.z = 5
const animate = time => {
const { width, height } = renderer.domElement
renderer.setViewport(0, 0, width, height)
camera.aspect = width / height
camera.updateProjectionMatrix()
cube.rotation.x = time / 2000
cube.rotation.y = time / 1000
renderer.render(scene, camera)
}
renderer.setAnimationLoop(animate)
}
const getRendererFPS = () => {
/** @type {import("@dandre3000/three-canvas-sandbox").ThreeCanvasSandboxContext} */
const { getFPS } = (globalThis)
return getFPS()
}
canvasSandbox.setRemoteFunction('demo', createScene)
canvasSandbox.setRemoteFunction('getFPS', getRendererFPS)
canvasSandbox.callRemoteFunction('demo')
const fpsDisplay = document.createElement('p')
document.body.appendChild(fpsDisplay)
setInterval(async () => {
fpsDisplay.innerText = await canvasSandbox.callRemoteFunction('getFPS')
}, 1000)Exports
Class ThreeCanvasSandbox extends import('@dandre3000/sandbox').SandboxPort
canvasContainer: HTMLDivElement
minCanvasWidth: string
minCanvasHeight: string
getCanvasWidth (): string
getCanvasHeight (): string
setLocalFunction (id: string, fn: Function | null): void
Create sandboxed function on the main thread or remove it if fn is null.
setRemoteFunction (id: string, fn: Function | null): Promise<void>
Create a sandboxed function on the canvas thread or remove it if fn is null.
callRemoteFunction (id: string): Promise<void>
Call a sandboxed function on the canvas thread.
