files/en-us/web/api/offscreencanvas/getcontext/index.md
{{APIRef("Canvas API")}}{{AvailableInWorkers}}
The OffscreenCanvas.getContext() method returns a drawing context for an offscreen canvas, or null if the context identifier is not supported, or the offscreen canvas has already been set to a different context mode.
getContext(contextType, contextAttributes)
contextType
: A string containing the context identifier defining the drawing context associated to the canvas. Possible values are:
2d
webgl
webgl2
"webgpu"
bitmaprenderer
[!NOTE] The identifiers
"experimental-webgl"or"experimental-webgl2"are also used in implementations of WebGL. These implementations have not reached test suite conformance, or the graphic drivers situation on the platform is not yet stable. The Khronos Group certifies WebGL implementations under certain conformance rules.
contextAttributes {{optional_inline}}
: You can use several context attributes when creating your rendering context, for example:
const gl = canvas.getContext("webgl", {
antialias: false,
depth: false,
});
2d context attributes:
alpha
false, the browser now knows that the backdrop is always opaque, which can speed up drawing of transparent content and images.colorSpace {{optional_inline}}
"srgb" selects the sRGB color space. This is the default value."display-p3" selects the display-p3 color space.colorType {{optional_inline}}
"unorm8" sets the color channels to 8 bit unsigned values. This is the default value."float16" sets the color channels to 16-bit floating-point values.desynchronized
willReadFrequently
WebGL context attributes:
alpha
depth
stencil
desynchronized
antialias
failIfMajorPerformanceCaveat
powerPreference
"default"
"high-performance"
"low-power"
premultipliedAlpha
preserveDrawingBuffer
xrCompatible
[!NOTE] The WebGPU specification does not define any specific context attributes for
getContext(). Instead, it provides configuration options via the {{domxref("GPUCanvasContext.configure()")}} method.
A rendering context which is either a
"2d","webgl" and "experimental-webgl","webgl2" and "experimental-webgl2","webgpu","bitmaprenderer".If the context identifier is not supported, or the canvas has already been set to a different context mode, null is returned.
InvalidStateError {{domxref("DOMException")}}
const offscreen = new OffscreenCanvas(256, 256);
const gl = offscreen.getContext("webgl");
gl; // WebGLRenderingContext
gl.canvas; // OffscreenCanvas
{{Specifications}}
{{Compat}}