Skip to content

Canvas.getContext ​

JS
    RenderingContext Canvas.getContext(string contextType, Object contextAttribute)

Gets the rendering context of a canvas object.

A single canvas can only obtain one rendering context.

  • When using the webgl or webgl2 context:
    1. The canvas corresponding to the current rendering context can be displayed on screen.
    2. If multiple canvases exist, other canvases attempting to obtain a webgl rendering context will get an empty object.
    3. Because WebGL rendering depends on the screen width and height, the width and height properties of the canvas corresponding to the current rendering context cannot be modified.
  • When using the 2d context:
    1. Content drawn via the current rendering context can only be stored in memory.
    2. The width and height properties of the canvas corresponding to the current rendering context can be modified.

Parameters

  • string contextType: The type of context to obtain. Valid values are as follows.

contextType valid values:

ValueDescription
2d2d rendering context
webglwebgl rendering context
experimental-webglwebgl rendering context
webgl2webgl2 rendering context
experimental-webgl2webgl2 rendering context
  • Object contextAttributes: Properties for the webgl or webgl2 context. Has no effect when contextType is 2d.

contextAttributes properties:

PropertyTypeDefaultDescription
alphabooleantrueWhether to include an alpha buffer
depthbooleantrueIf true, the drawing buffer includes a depth buffer of at least 16 bits
stencilbooleantrueIf true, the drawing buffer includes a stencil buffer of at least 8 bits
antialiasbooleanfalseWhether to enable antialiasing
preserveDrawingBufferbooleanfalseIf true, the buffer will not be cleared and will be preserved until it is cleared or overwritten by the user

Return Value

  • RenderingContext: The rendering context