Offscreen Canvas Polyfill
JS polyfill (375 bytes) for OffscreenCanvas
to move Three.js,
WebGL or 2D canvas to Web Worker.
It will improve performance in Chrome and will load worker by <script>
in Firefox, Safari, and other browsers.
The tutorial for this library: Faster WebGL/Three.js 3D graphics with OffscreenCanvas and Web Workers.
// index.js const worker = button
// worker.js const worker =
Usage
Create separated bundle in webpack, Parcel or any other bundler:
entry: { app: './src/app.js',+ worker: './src/worker.js' }
Move all code working with <canvas>
to worker.js
. It means to move all WebGL
or Three.js imports and scene related code.
// Move Three.js imports here if you use Three.js const worker =
Some of Three.js code (mostly loaders) will not work in Web Worker.
Use worker.isWorker
to switch loaders:
if workerisWorker loader = else loader =
Put preload link to HTML templates with a URL to worker.js
.
Your bundle will add cache buster to bundle names, so bundle names will
change every time you deploy application. This is why we need to store
path to worker.js
in HTML:
+ <link type="preload" as="script" href="./worker.js"> </head>
Load worker in main app.js
:
const workerUrl = documenthrefconst canvas = document const worker =
Keep all UI interaction code (listeners for clicks, mouse move, etc)
in app.js
. Send message to Worker when your need to update <canvas>
after user actions:
button
Process this messages in the worker:
const worker = insideWorker(e => { if (e.data.canvas) { // Move scene building code here- }+ } else if (e.data.message === 'move') {+ // Move object on the scene+ } })