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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
|
---
title: Рисование текста
slug: Web/API/Canvas_API/Tutorial/Drawing_text
tags:
- Canvas
- Графика
- Примеры
- Руководство
- мануал
translation_of: Web/API/Canvas_API/Tutorial/Drawing_text
original_slug: Web/API/Canvas_API/Tutorial/Рисование_текста
---
<div>{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Applying_styles_and_colors", "Web/API/Canvas_API/Tutorial/Using_images")}}</div>
<div class="summary">
<p>После того, как мы увидели в предыдущей главе, как <a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors">применять стили и цвета</a>, взглянем на написание текста в canvas.</p>
</div>
<h2 id="Рисование_текста">Рисование текста</h2>
<p>Контекст рендеринга canvas предоставляет два метода для рисования текста:</p>
<dl>
<dt>{{domxref("CanvasRenderingContext2D.fillText", "fillText(text, x, y [, maxWidth])")}}</dt>
<dd>Вставляет заданный текст в положении (x,y). Опционально может быть указана максимальная ширина.</dd>
<dt>{{domxref("CanvasRenderingContext2D.strokeText", "strokeText(text, x, y [, maxWidth])")}}</dt>
<dd>Вставляет контур заданного текста в положении (x,y). Опционально может быть указана максимальная ширина.</dd>
</dl>
<h3 id="Пример_fillText">Пример <code>fillText</code></h3>
<p>Текст вставлен с использованием текущего <code>fillStyle</code>.</p>
<pre class="brush: js;highlight[4]">function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.font = "48px serif";
ctx.fillText("Hello world", 10, 50);
}</pre>
<div class="hidden">
<pre class="brush: html"><canvas id="canvas" width="300" height="100"></canvas></pre>
<pre class="brush: js">draw();</pre>
</div>
<p>{{EmbedLiveSample("Пример_fillText", 310, 110)}}</p>
<h3 id="Пример_strokeText">Пример <code>strokeText</code></h3>
<p>Текст вставлен с использованием текущего <code>strokeStyle</code>.</p>
<pre class="brush: js;highlight[4]">function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.font = "48px serif";
ctx.strokeText("Hello world", 10, 50);
}</pre>
<div class="hidden">
<pre class="brush: html"><canvas id="canvas" width="300" height="100"></canvas></pre>
<pre class="brush: js">draw();</pre>
</div>
<p>{{EmbedLiveSample("Пример_strokeText", 310, 110)}}</p>
<h2 id="Стилизация_текста">Стилизация текста</h2>
<p>В примерах выше мы уже использовали свойство font для изменения размера текста. Кроме него существуют ещё несколько свойств, позволяющие настроить вывод текста на canvas:</p>
<dl>
<dt>{{domxref("CanvasRenderingContext2D.font", "font = value")}}</dt>
<dd>Это основной стиль, который будет использоваться для вывода текста. Строка имеет такой же синтаксис, как <a href="/en-US/docs/Web/CSS">CSS</a>-свойство {{cssxref("font")}}. По умолчанию - sans-serif высотой 10px.</dd>
<dt>{{domxref("CanvasRenderingContext2D.textAlign", "textAlign = value")}}</dt>
<dd>Настройка выравнивания текста. Возможные значения: <code>start</code>, <code>end</code>, <code>left</code>, <code>right</code> или <code>center</code>. По умолчанию - <code>start</code>.</dd>
<dt>{{domxref("CanvasRenderingContext2D.textBaseline", "textBaseline = value")}}</dt>
<dd>Настройка выравнивания текста по вертикали. Возможные значения: <code>top</code>, <code>hanging</code>, <code>middle</code>, <code>alphabetic</code>, <code>ideographic</code>, <code>bottom</code>. По умолчанию - <code>alphabetic</code>.</dd>
<dt>{{domxref("CanvasRenderingContext2D.direction", "direction = value")}}</dt>
<dd>Направление текста. Возможные значения: <code>ltr</code>, <code>rtl</code>, <code>inherit</code>. По умолчанию - <code>inherit</code>.</dd>
</dl>
<p>Эти свойства могут быть вам знакомы если вы работали с CSS.</p>
<p>Изображение от <a class="external" href="http://www.whatwg.org/">WHATWG</a> ниже показывает различные варианты свойства <code>textBaseline</code>.<img alt="The top of the em square is
roughly at the top of the glyphs in a font, the hanging baseline is
where some glyphs like आ are anchored, the middle is half-way
between the top of the em square and the bottom of the em square,
the alphabetic baseline is where characters like Á, ÿ,
f, and Ω are anchored, the ideographic baseline is
where glyphs like 私 and 達 are anchored, and the bottom
of the em square is roughly at the bottom of the glyphs in a
font. The top and bottom of the bounding box can be far from these
baselines, due to glyphs extending far outside the em square." src="http://www.whatwg.org/specs/web-apps/current-work/images/baselines.png"></p>
<h3 id="Пример_textBaseline">Пример textBaseline</h3>
<p>Редактируя код ниже, вы можете видеть, как меняется отображение текста на canvas в реальном времени:</p>
<pre class="brush: js;highlight[2]">ctx.font = "48px serif";
ctx.textBaseline = "hanging";
ctx.strokeText("Hello world!", 0, 100);
</pre>
<div class="hidden">
<h6 id="Playable_code">Playable code</h6>
<pre class="brush: html"><canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
<div class="playable-buttons">
<input id="edit" type="button" value="Edit" />
<input id="reset" type="button" value="Reset" />
</div>
<textarea id="code" class="playable-code">
ctx.font = "48px serif";
ctx.textBaseline = "hanging";
ctx.strokeText("Hello world", 0, 100);</textarea>
</pre>
<pre class="brush: js">var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var textarea = document.getElementById("code");
var reset = document.getElementById("reset");
var edit = document.getElementById("edit");
var code = textarea.value;
function drawCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
eval(textarea.value);
}
reset.addEventListener("click", function() {
textarea.value = code;
drawCanvas();
});
edit.addEventListener("click", function() {
textarea.focus();
})
textarea.addEventListener("input", drawCanvas);
window.addEventListener("load", drawCanvas);
</pre>
</div>
<p>{{ EmbedLiveSample('Playable_code', 700, 360) }}</p>
<h2 id="Измерение_ширины_текста">Измерение ширины текста</h2>
<p>Для измерения ширины текста (без рисования его на canvas) можно воспользоваться следующим методом:</p>
<dl>
<dt>{{domxref("CanvasRenderingContext2D.measureText", "measureText()")}}</dt>
<dd>Возвращает объект {{domxref("TextMetrics")}}, содержащий ширину текста в пикселах, до отрисовки на canvas.</dd>
</dl>
<p>Пример ниже показывает, как можно измерить ширину текста.</p>
<pre class="brush: js;highlight[3]">function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
var text = ctx.measureText("foo"); // TextMetrics object
text.width; // 16;
}
</pre>
<h2 id="Примечания">Примечания</h2>
<p>В ранних версиях Gecko (движок рендеринга в Firefox, Firefox OS и других приложениях Mozilla) были реализованы <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D#Prefixed_APIs">методы API с префиксами</a> для рисования текста на canvas. На данный момент они устарели и уже, возможно, удалены, поэтому их правильная работа не гарантируется.</p>
<p>{{PreviousNext("Web/API/Canvas_API/Tutorial/Applying_styles_and_colors", "Web/API/Canvas_API/Tutorial/Using_images")}}</p>
|