A minimal javascript library that makes it pretty easy for you to create a custom element that creates an offline canvas in a web worker and renders it in the animation frame loop of the browser.
Whether webgl, webgpu or 2d context is up to the user, the class takes care of the synchronization of the element dimension and rendering of the frames.
➜ npm i -D @spearwolf/offscreen-display
To get started quickly, vite is recommended, but this is purely optional and a matter of taste.
just updated? there is also a CHANGELOG
awesome-display.js
import {OffscreenDisplay} from '@spearwolf/offscreen-display';
class AwesomeDisplay extends OffscreenDisplay {
createWorker() {
return new Worker(new URL('awesome-display-worker.js', import.meta.url), {
type: 'module',
});
}
}
customElements.define('awesome-display', AwesomeDisplay);
index.html
<html>
<body>
<awesome-display></awesome-display>
<script type="module" src="awesome-display.js"></script>
</body>
</html>
awesome-display-worker.js
import {OffscreenWorkerDisplay} from '@spearwolf/offscreen-display/worker.js';
const display = new OffscreenWorkerDisplay();
let ctx = null;
display.on({
onCanvas({canvas}, contextAttributes) {
ctx = canvas.getContext('2d', contextAttributes);
},
onFrame({now, canvasWidth: w, canvasHeight: h}) {
ctx.clearRect(0, 0, w, h);
},
});
self.addEventListener('message', (evt) => {
display.parseMessageData(evt.data);
});
There are other features not listed here. For a complete example, see the rainbow line element.
Copyright © 2024 by Wolfger Schramm.
The source code and npm package is licensed under the Apache-2.0 License.
have fun! 🚀🌱