HTMLCanvasElement.getContext()

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

* Some parts of this feature may have varying levels of support.

Метод HTMLCanvasElement.getContext() возвращает контекст рисования на холсте, или null, если идентификатор контекста не определён.

Синтаксис

canvas.getContext(contextType, contextAttributes);

Параметры

contextType

DOMString, содержащий идентификатор контекста, определяющий контекст рисования, связанный с холстом. Возможные значения:

  • "2d", ведущий к созданию объекта CanvasRenderingContext2D, представляющий двумерный контекст.
  • "webgl" (или "experimental-webgl"), который будет создавать объект WebGLRenderingContext, представляющий трёхмерный контекст. Этот контекст доступен только в браузерах, которые реализуют WebGL первой версии (OpenGL ES 2.0).
  • "webgl2" (или "experimental-webgl2"), который будет создавать объект WebGL2RenderingContext, представляющий трёхмерный контекст. Этот контекст доступен только в браузерах, которые реализуют WebGL второй версии (OpenGL ES 3.0). Экспериментальная возможность
  • "bitmaprenderer", который позволит создать ImageBitmapRenderingContext, обеспечивающий только функции для замены содержимого холста с заданным ImageBitmap.

Примечание: Идентификаторы "experimental-webgl" или "experimental-webgl2" используются в новых реализациях WebGL. Эти реализации не достигли испытательного набора на соответствие или ситуация с графическими драйверами на платформе ещё не стабильна The Khronos Group certifies WebGL implementations under certain conformance rules.

contextAttributes

Вы можете использовать несколько атрибутов контекста при создании контекста рендеринга, например:

js
canvas.getContext("webgl", { antialias: false, depth: false });

2d атрибуты контекста:

  • alpha: Логическое значение, означающее, есть ли у холста альфа-канал. Значение false говорит браузеру, что фон холста непрозрачный, что может ускорить рисование прозрачного содержимого и изображений.
  • Не стандартно (Gecko only) willReadFrequently: Boolean that indicates whether or not a lot of read-back operations are planned. This will force the use of a software (instead of hardware accelerated) 2D canvas and can save memory when calling getImageData() frequently. This option is only available, if the flag gfx.canvas.willReadFrequently.enable is set to true (which, by default, is only the case for B2G/Firefox OS).
  • Не стандартно (Blink only) storage: String that indicates which storage is used ("persistent" by default).

Атрибуты контекста WebGL:

  • alpha: Boolean that indicates if the canvas contains an alpha buffer.
  • depth: Boolean that indicates that the drawing buffer has a depth buffer of at least 16 bits.
  • stencil: Boolean that indicates that the drawing buffer has a stencil buffer of at least 8 bits.
  • antialias: Boolean that indicates whether or not to perform anti-aliasing.
  • premultipliedAlpha: Boolean that indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha.
  • preserveDrawingBuffer: If the value is true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author.
  • failIfMajorPerformanceCaveat: Boolean that indicates if a context will be created if the system performance is low.

Возвращаемое значение

Контекст рендеринга, который представляет собой

Если contextType не соответствует возможному контексту рисунка, то возвращается null.

Примеры

Given this <canvas> element:

html
<canvas id="canvas" width="300" height="300"></canvas>

You can get a 2d context of the canvas with the following code:

js
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
console.log(ctx); // CanvasRenderingContext2D { ... }

Now you have the 2D rendering context for a canvas and you can draw within it.

Спецификации

Specification
HTML
# dom-canvas-getcontext-dev

Совместимость с браузерами

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
getContext
2d context
options.alpha parameter
options.colorSpace parameter
options.desynchronized parameter
options.willReadFrequently parameter
bitmaprenderer context
options.alpha parameter
WebGL2 context
options.alpha parameter
options.desynchronized parameter
options.failIfMajorPerformanceCaveat parameter
options.powerPreference parameter
WebGL context
options.alpha parameter
options.desynchronized parameter
options.failIfMajorPerformanceCaveat parameter
options.powerPreference parameter
webgpu context
Experimental

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
In development. Supported in a pre-release version.
In development. Supported in a pre-release version.
No support
No support
Experimental. Expect behavior to change in the future.
See implementation notes.
Uses a non-standard name.
Has more compatibility info.

Смотрите также