OffscreenCanvas: transferToImageBitmap() method
Baseline 2023
Newly available
Since March 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
Note: This feature is available in Web Workers.
The OffscreenCanvas.transferToImageBitmap()
method creates an ImageBitmap
object from the most recently rendered image of the OffscreenCanvas
. The OffscreenCanvas
allocates a new image for its subsequent rendering.
Syntax
transferToImageBitmap()
Parameters
None.
Return value
A newly-allocated ImageBitmap
.
This ImageBitmap
references a potentially large graphics resource, and to ensure your web application remains robust, it is important to avoid allocating too many of these resources at any point in time. For this reason it is important to ensure that the ImageBitmap
is either consumed or closed.
As described in the OffscreenCanvas
examples, passing this ImageBitmap
to ImageBitmapRenderingContext.transferFromImageBitmap()
consumes the ImageBitmap
object; it no longer references the underlying graphics resource, and can not be passed to any other web APIs.
If your goal is to pass the ImageBitmap
to other web APIs which do not consume it - for example, CanvasRenderingContext2D.drawImage()
- then you should close it when you're done with it by calling ImageBitmap.close()
. Don't simply drop the JavaScript reference to the ImageBitmap
; doing so will keep its graphics resource alive until the next time the garbage collector runs.
If you call transferToImageBitmap()
and don't intend to pass it to ImageBitmapRenderingContext.transferFromImageBitmap()
, consider whether you need to call transferToImageBitmap()
at all. Many web APIs which accept ImageBitmap
also accept OffscreenCanvas
as an argument.
Exceptions
InvalidStateError
DOMException
-
Throws if:
- the canvas has transferred to another context scope, such as a worker
- the canvas context mode has not been set by calling
OffscreenCanvas.getContext()
.
Examples
const offscreen = new OffscreenCanvas(256, 256);
const gl = offscreen.getContext("webgl");
// Perform some drawing using the gl context
offscreen.transferToImageBitmap();
// ImageBitmap { width: 256, height: 256 }
// Either:
// Pass this `ImageBitmap` to `ImageBitmapRenderingContext.transferFromImageBitmap`
// or:
// Use the `ImageBitmap` with other web APIs, and call `ImageBitmap.close()`!
Specifications
Specification |
---|
HTML Standard # dom-offscreencanvas-transfertoimagebitmap-dev |
Browser compatibility
BCD tables only load in the browser
See also
- The interface defining this method,
OffscreenCanvas
ImageBitmapRenderingContext.transferFromImageBitmap