Carsten Ruhr

The Offscreen Canvas

For the Mythical Ink Dungeon Generator I made heavy use of the canvas element. For drawing the final dungeon as well as drawing partials and masks to not-visible canvas elements to add them all up together to a final result.

Those invisible canvases are called “offscreen canvas” and they are usually generated like this:

const myOffscreenCanvas = document.createElement('canvas')
myOffscreenCanvas.width = 640
myOffscreenCanvas.height = 480
const myOffscreenContext = myOffscreenCanvas.getContext('2d')

That’s actually not too bad. 4 lines to start drawing on an invisible canvas.

But around comes the dedicated OffscreenCanvas interface. This allows you to create the canvas like this:

const myOffscreenCanvas = new OffscreenCanvas(640, 480)
const myOffscreenContext = myOffscreenCanvas.getContext('2d')

It saves us two lines but otherwise delivers the same result as the method above. So why do we need a dedicated interface for this?

If you look closely there is another difference. The first method creates an HTML element via the DOM and relies on the global document object. In workers (or in a browserless context such as nodejs) you don’t have a DOM by default. So now with the OffscreenCanvas interface you can easily put rendering logic into a service worker and keep it away from the main thread. That’s gold! Animating things and rendering them to a canvas can have significant performance impacts if it get’s done on the same thread as the UI.

Unfortunately, this is still an experimental feature at the time I'm writing this post. Safari doesn’t support it at all and Firefox only partially, while Chrome and Edge are already full in on it.