bergben
bergben

Reputation: 1415

Use Canvas in Web Worker

Is there any way to use a Canvas Element inside of a Web Worker? I want to do canvas.toBlob inside of a Web Worker to reduce the quality of an image.

Like maybe somehow through https://github.com/substack/webworkify webworkify? Which allows to require other libraries inside a web worker?

I either need to pass a canvas elment to a Web Worker, or create a canvas Element inside of the Web Worker, or find an alternative way to reduce the quality of an image.

Upvotes: 7

Views: 5914

Answers (1)

Paul Sweatte
Paul Sweatte

Reputation: 24637

Use OffscreenCanvas:

OffscreenCanvas objects are used to create rendering contexts, much like an HTMLCanvasElement, but with no connection to the DOM. This makes it possible to use canvas rendering contexts in workers.

An OffscreenCanvas object may hold a weak reference to a placeholder canvas element, which is typically in the DOM, whose embedded content is provided by the OffscreenCanvas object. The bitmap of the OffscreenCanvas object is pushed to the placeholder canvas element by calling the commit() method of the OffscreenCanvas object's rendering context. All rendering context types that can be created by an OffscreenCanvas object must implement a commit() method. The exact behavior of the commit method (e.g. whether it copies or transfers bitmaps) may vary, as defined by the rendering contexts' respective specifications. Only the 2D context for offscreen canvases is defined in this specification.

This is an experimental feature, so it is hidden behind a flag. It is supported by Firefox:

This feature is behind a feature preference setting. In about:config, set gfx.offscreencanvas.enabled to true.

And Chrome:

This feature is behind a flag. In chrome://flags click enable under Experimental canvas features

For the worker use cases, there is no dependency on the DOM:

Web workers are not DOM-dependent. They handle pure data, which makes them especially suitable for JavaScript code that takes a long time to execute.

Only Firefox supports the ImageData manipulation.

Canvas Web Worker Support

References

Upvotes: 5

Related Questions