Creates an ImageBitmap object from the most recently rendered image of the OffscreenCanvas.
Examples
Synchronous display of frames produced by an OffscreenCanvas
One way to use the OffscreenCanvas API, is to use a rendering context that has been obtained from an OffscreenCanvas object to generate new frames. Once a new frame has finished rendering in this context, the transferToImageBitmap() method can be called to save the most recent rendered image. This method returns an ImageBitmap object, which can be used in a variety of Web APIs and also in a second canvas without creating a transfer copy.
To display the ImageBitmap, you can use a ImageBitmapRenderingContext context, which can be created by calling canvas.getContext("bitmaprenderer") on a (visible) canvas element. This context only provides functionality to replace the canvas's contents with the given ImageBitmap. A call to ImageBitmapRenderingContext.transferFromImageBitmap() with the previously rendered and saved ImageBitmap from the OffscreenCanvas, will display the ImageBitmap on the canvas and transfer its ownership to the canvas. A single OffscreenCanvas may transfer frames into an arbitrary number of other ImageBitmapRenderingContext objects.
the following code will provide the rendering using an OffscreenCanvas as described above.
var one = document.getElementById("one").getContext("bitmaprenderer");var two = document.getElementById("two").getContext("bitmaprenderer");var offscreen =newOffscreenCanvas(256,256);var gl = offscreen.getContext('webgl');// ... some drawing for the first canvas using the gl context ...// Commit rendering to the first canvasvar bitmapOne = offscreen.transferToImageBitmap();
one.transferFromImageBitmap(bitmapOne);// ... some more drawing for the second canvas using the gl context ...// Commit rendering to the second canvasvar bitmapTwo = offscreen.transferToImageBitmap();
two.transferFromImageBitmap(bitmapTwo);
Asynchronous display of frames produced by an OffscreenCanvas
Another way to use the OffscreenCanvas API, is to call transferControlToOffscreen() on a <canvas> element, either on a worker or the main thread, which will return an OffscreenCanvas object from an HTMLCanvasElement object from the main thread. Calling getContext() will then obtain a rendering context from that OffscreenCanvas.
onmessage=function(evt){var canvas = evt.data.canvas;var gl = canvas.getContext("webgl");// ... some drawing using the gl context ...};
You can also use requestAnimationFrame in workers
onmessage=function(evt){const canvas = evt.data.canvas;const gl = canvas.getContext("webgl");functionrender(time){// ... some drawing using the gl context ...requestAnimationFrame(render);}requestAnimationFrame(render);};