Skip to content

Latest commit

 

History

History

offscreen-display

@spearwolf/offscreen-display

npm (scoped) License

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.

📖 How To

1. Install

➜ 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

2. Create custom element

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);

3. Integrate the element in your page

index.html

<html>
  <body>
    <awesome-display></awesome-display>
    <script type="module" src="awesome-display.js"></script>
  </body>
</html>

3. Create your worker

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);
});

4. More features available

There are other features not listed here. For a complete example, see the rainbow line element.

Copyright and License

Copyright © 2024 by Wolfger Schramm.

The source code and npm package is licensed under the Apache-2.0 License.

have fun! 🚀🌱