aboutsummaryrefslogtreecommitdiff
path: root/files/ru/web/api/htmlcanvaselement/getcontext/index.html
blob: c1fc3042ee63b236a1bfcb99c38dc73797f98642 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
---
title: HTMLCanvasElement.getContext()
slug: Web/API/HTMLCanvasElement/getContext
translation_of: Web/API/HTMLCanvasElement/getContext
---
<div>{{APIRef("Canvas API")}}</div>

<p>Метод <strong><code>HTMLCanvasElement.getContext()</code></strong> возвращает контекст рисования на холсте, или {{jsxref("null")}}, если идентификатор контекста не определён.</p>

<h2 id="Синтаксис">Синтаксис</h2>

<pre class="syntaxbox"><var><em>canvas</em>.getContext(<em>contextType, contextAttributes</em>);</var>
</pre>

<h3 id="Параметры">Параметры</h3>

<dl>
 <dt>contextType</dt>
 <dd>{{domxref("DOMString")}}, содержащий идентификатор контекста, определяющий контекст рисования, связанный с холстом. Возможные значения:
 <ul>
  <li><code>"2d</code>", ведущий к созданию объекта {{domxref("CanvasRenderingContext2D")}}, представляющий двумерный контекст.</li>
  <li><code>"webgl"</code> (или <code>"experimental-webgl"</code>), который будет создавать объект {{domxref("WebGLRenderingContext")}}, представляющий трёхмерный контекст. Этот контекст доступен только в браузерах, которые реализуют {{domxref("WebGL")}} первой версии (OpenGL ES 2.0).</li>
  <li>"<code>webgl2</code>" (или "<code>experimental-webgl2</code>"), который будет создавать объект {{domxref("WebGL2RenderingContext")}}, представляющий трёхмерный контекст. Этот контекст доступен только в браузерах, которые реализуют {{domxref("WebGL")}} второй версии (OpenGL ES 3.0). {{experimental_inline}}</li>
  <li><code>"bitmaprenderer",</code> который позволит создать {{domxref("ImageBitmapRenderingContext")}}, обеспечивающий только функции для замены содержимого холста с заданным {{domxref("ImageBitmap")}}.</li>
 </ul>

 <p>Примечание: Идентификаторы "<code>experimental-webgl</code>" или "<code>experimental-webgl2</code>" используются в новых реализациях WebGL. Эти реализации не достигли испытательного набора на соответствие или ситуация с графическими драйверами на платформе ещё не стабильна The <a href="https://www.khronos.org/">Khronos Group</a> certifies WebGL implementations under certain <a href="https://www.khronos.org/registry/webgl/sdk/tests/CONFORMANCE_RULES.txt">conformance rules</a>.</p>
 </dd>
 <dt><code>contextAttributes</code></dt>
 <dd>
 <p>Вы можете использовать несколько атрибутов контекста при создании контекста рендеринга, например:</p>

 <pre class="brush: js">canvas.getContext("webgl",
                 { antialias: false,
                   depth: false });</pre>
 2d атрибуты контекста:

 <ul>
  <li><strong><code>alpha</code></strong>: Логическое значение, означающее, есть ли у холста альфа-канал. Значение <code>false</code> говорит браузеру, что фон холста непрозрачный, что может ускорить рисование прозрачного содержимого и изображений.</li>
  <li>{{non-standard_inline}} (Gecko only) <strong><code>willReadFrequently</code></strong>: 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 {{domxref("CanvasRenderingContext2D.getImageData", "getImageData()")}} frequently. This option is only available, if the flag <code>gfx.canvas.willReadFrequently.enable</code> is set to <code>true</code> (which, by default, is only the case for B2G/Firefox OS).</li>
  <li>{{non-standard_inline}} (Blink only) <strong><code>storage</code></strong>: String that indicates which storage is used ("persistent" by default).</li>
 </ul>
 Атрибуты контекста WebGL:

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

<h3 id="Возвращаемое_значение">Возвращаемое значение</h3>

<p>{{domxref("RenderingContext")}}, который представляет собой</p>

<ul>
 <li>{{domxref("CanvasRenderingContext2D")}} для <code>"2d"</code>,</li>
 <li>{{domxref("WebGLRenderingContext")}} для <code>"webgl"</code> и <code>"experimental-webgl"</code>,</li>
 <li>{{domxref("WebGL2RenderingContext")}} для <code>"webgl2"</code> и <code>"experimental-webgl2"</code>, или</li>
 <li>{{domxref("ImageBitmapRenderingContext")}} для <code>"bitmaprenderer"</code>.</li>
</ul>

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

<h2 id="Примеры">Примеры</h2>

<p>Given this {{HTMLElement("canvas")}} element:</p>

<pre class="brush: html">&lt;canvas id="canvas" width="300" height="300"&gt;&lt;/canvas&gt;
</pre>

<p>You can get a <code>2d</code> context of the canvas with the following code:</p>

<pre class="brush: js">var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
console.log(ctx); // CanvasRenderingContext2D { ... }
</pre>

<p>Now you have the <a href="/en-US/docs/Web/API/CanvasRenderingContext2D">2D rendering context</a> for a canvas and you can draw within it.</p>

<h2 id="Спецификации">Спецификации</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}</td>
   <td>{{Spec2('HTML WHATWG')}}</td>
   <td>No change since the latest snapshot, {{SpecName('HTML5 W3C')}}</td>
  </tr>
  <tr>
   <td>{{SpecName('HTML5.1', "scripting-1.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}</td>
   <td>{{Spec2('HTML5.1')}}</td>
   <td> </td>
  </tr>
  <tr>
   <td>{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}</td>
   <td>{{Spec2('HTML5 W3C')}}</td>
   <td>Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.</td>
  </tr>
 </tbody>
</table>

<h2 id="Совместимость_браузеров">Совместимость браузеров</h2>

<p>{{Compat("api.HTMLCanvasElement.getContext")}}</p>

<h2 id="Смотрите_также">Смотрите также</h2>

<ul>
 <li>The interface defining it, {{domxref("HTMLCanvasElement")}}.</li>
 <li>{{domxref("OffscreenCanvas.getContext()")}}</li>
 <li>Available rendering contexts: {{domxref("CanvasRenderingContext2D")}}, {{domxref("WebGLRenderingContext")}} and {{domxref("WebGL2RenderingContext")}} and {{domxref("ImageBitmapRenderingContext")}}.</li>
</ul>