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
168
169
170
|
---
title: Drawing text
slug: Web/API/Canvas_API/Tutorial/Drawing_text
tags:
- Canvas
- Intermediário
- Tutorial
- graficos
translation_of: Web/API/Canvas_API/Tutorial/Drawing_text
original_slug: Web/Guide/HTML/Canvas_tutorial/Drawing_text
---
<div>{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Applying_styles_and_colors", "Web/API/Canvas_API/Tutorial/Using_images")}}</div>
<div class="summary">
<p>Após entender como <a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors">aplicar estilos e cores</a> no capítulo anterior, nós veremos agora como desenhar texto dentro do contexto de uma canvas.</p>
</div>
<h2 id="Desenhando_texto">Desenhando texto</h2>
<p>O context de renderização da canvas fornece dois métodos para renderização textual: </p>
<dl>
<dt>{{domxref("CanvasRenderingContext2D.fillText", "fillText(text, x, y [, maxWidth])")}}</dt>
<dd>Preenche com um determinado texto as cordenadas (x,y) recebidas. Opcionalmente com uma largura máxima para o desenho.</dd>
<dt>{{domxref("CanvasRenderingContext2D.strokeText", "strokeText(text, x, y [, maxWidth])")}}</dt>
<dd>Traçeja um determinado texto nas cordenadas (x,y) recebidas. Opcionalmente com uma largura máxima para o desenho.</dd>
</dl>
<h3 id="Um_exemplo_com_fillText">Um exemplo com <code>fillText</code></h3>
<p>O texto a seguir é rederizado utilizando <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("A_fillText_example", 310, 110)}}</p>
<h3 id="Um_exemplo_com_strokeText">Um exemplo com <code>strokeText</code></h3>
<p> </p>
<p dir="ltr" id="tw-target-text">O texto é preenchido usando o strokeStyle atual.</p>
<p> </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("A_strokeText_example", 310, 110)}}</p>
<h2 id="Estilo_de_Texto"><strong>Estilo de Texto</strong></h2>
<p>Nos exemplos anteriores, já usamos a propriedade font para tornar o texto um pouco maior que o tamanho padrão. Existem mais algumas propriedades que permitem ajustar a maneira como o texto é exibido no canvas:</p>
<dl>
<dt>{{domxref("CanvasRenderingContext2D.font", "font = value")}}</dt>
<dd>The current text style being used when drawing text. This string uses the same syntax as the <a href="/en-US/docs/Web/CSS">CSS</a> {{cssxref("font")}} property. The default font is 10px sans-serif.</dd>
<dt>{{domxref("CanvasRenderingContext2D.textAlign", "textAlign = value")}}</dt>
<dd>Text alignment setting. Possible values: <code>start</code>, <code>end</code>, <code>left</code>, <code>right</code> or <code>center</code>. The default value is <code>start</code>.</dd>
<dt>{{domxref("CanvasRenderingContext2D.textBaseline", "textBaseline = value")}}</dt>
<dd>Baseline alignment setting. Possible values: <code>top</code>, <code>hanging</code>, <code>middle</code>, <code>alphabetic</code>, <code>ideographic</code>, <code>bottom</code>. The default value is <code>alphabetic</code>.</dd>
<dt>{{domxref("CanvasRenderingContext2D.direction", "direction = value")}}</dt>
<dd>Directionality. Possible values: <code>ltr</code>, <code>rtl</code>, <code>inherit</code>. The default value is <code>inherit</code>.</dd>
</dl>
<p>Essas propriedades podem ser similares para você, se você trabalhou com CSS antes.</p>
<p>O diagrama seguinte do <a class="external" href="http://www.whatwg.org/">WHATWG</a> demonstra as várias baselines suportadas pela propriedade do <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="O_exemplo_de_uma_textBaseline">O exemplo de uma textBaseline</h3>
<p>Edite o código abaixo e veja as atualizações em tempo real no 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" name="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="Advanced_text_measurements">Advanced text measurements</h2>
<p>In the case you need to obtain more details about the text, the following method allows you to measure it.</p>
<dl>
<dt>{{domxref("CanvasRenderingContext2D.measureText", "measureText()")}}</dt>
<dd>Returns a {{domxref("TextMetrics")}} object containing the width, in pixels, that the specified text will be when drawn in the current text style.</dd>
</dl>
<p>The following code snippet shows how you can measure a text and get its width.</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="Notas_específicas_-_Gecko">Notas específicas - Gecko</h2>
<p>No Gecko (a engine de renderização do Firefox, Firefox OS e outras aplicações Mozilla), algumas APIs prefixadas foram implementadas em versões anteriores para escrever texto em um canvas. Essas APIs agora estão depreciadas e removidas, e não são mais garantidas para uso.</p>
<p>{{PreviousNext("Web/API/Canvas_API/Tutorial/Applying_styles_and_colors", "Web/API/Canvas_API/Tutorial/Using_images")}}</p>
|