Improve JavaScript Performance with OffscreenCanvas
Learn how to improve the performance of rendering in canvas by using OffscreenCanvas
The OffscreenCanvas interface allows canvas rendering contexts (2D and WebGL) to be used in Workers. It increases parallelism in the web, leading to improved performance on multi-core systems.
Using OffscreenCanvas we can render a canvas in the worker thread so that the main thread will be undisturbed so that our web app will work smoothly.
The support of OffscreenCanvas across the browser can be found here CanIUse.
There are two ways we can use OffscreenCanvas
- Creating an OffscreenCanvas from existing canvas
- Creating an OffscreenCanvas manually and render that to the existing canvas
1. Creating an OffscreenCanvas from existing canvas
We can call the transferControlToOffscreen
method on the canvas element to get an OffscreenCanvas
element which can be transferred to the worker. Operations applied to OffscreenCanvas
will be rendered on the source canvas automatically.
Example
In the above code, we have created a offscreenCanvas
from the canvas
element, which is transferred to the worker and the rendering will happen in the worker thread.
In offscreen_worker.js file
Note: If you have already used getContext
on this canvas, you will not be able to transfer it to the worker.
2. Creating an OffscreenCanvas manually and render that to the existing canvas
The second way is to create a OffscreenCanvas
object and render in that canvas then fetch the image data from the offscreenCanvas
and render it back to the original canvas. By using this way, we can render in multiple canvases at once.
To display the image(ImageBitmap
) from offscreenCanvas
, you can use a ImageBitmapRenderingContext
context, which can be created by calling canvas.getContext("bitmaprenderer")
on an original canvas element. This context only provides functionality to replace the canvas's contents with the given ImageBitmap
.
In the worker, we will use the canvas and do some animation:
You can use offscreenCanvas
in your web app, if your app involves some complex rendering operations in canvas.
Thanks for reading. Follow Javascript Jeep🚙💨 .