--- title: Desenhando texto usando canvas slug: Desenhando_texto_usando_canvas tags: - 'HTML:Canvas' - PrecisaDeConteúdo ---

{{ Gecko_minversion_header("1.9") }} O elemento <canvas> dá suporte a desenho de texto através da API experimental Mozilla-specific.

API

attribute DOMString mozTextStyle;
void mozDrawText(in DOMString textToDraw);
float mozMeasureText(in DOMString textToMeasure);
void mozPathText(in DOMString textToPath);
void mozTextAlongPath(in DOMString textToDraw, in boolean stroke);

Notas

Demonstrações

Veja alguns exemplos here, here, and here.

Alterando a fonte corrente

The mozTextStyle attribute reflects the current text style. It uses the same syntax as the CSS font specifier.

Ex:

ctx.mozTextStyle = "20pt Arial"

Desenhando o texto

Drawing is very simple. mozDrawText uses whatever the current text style is. The context's fill color is used as the text color.

ctx.translate(10, 50);
ctx.fillStyle = "Red";
ctx.mozDrawText("Sample String");

Medindo o texto

As vezes é de grande valia saber a largura de um bit de texto em particular (para centralizá-lo em uma janela).

var text = "Sample String";
var width = ctx.canvas.width;
var len = ctx.mozMeasureText(text);
ctx.translate(len/2, 0);
ctx.mozDrawText(text);

Text/path interaction

If you want to stroke text, mozDrawText doesn't let you. However, mozPathText adds the strokes from the text to the current path.

ctx.fillStyle = "green";
ctx.strokeStyle = "black";
ctx.mozPathText("Sample String");
ctx.fill()
ctx.stroke()

Now say you have a path that you want to add text along (say a curved line or something); this is where mozTextAlongPath comes in. Unlike the other text functions, mozTextAlongPath takes two arguments: the text and what to do with it. mozTextAlongPath approximates the current path as a series of line segments and places each glyph along that flattened path. The glyphs are not scaled or transformed according to the curvature of their baseline; they take on the orientation of the flattened path at the midpoint of the glyph.

Once mozTextAlongPath knows where the glyphs are, it looks at the second parameter to decide what to do with them. If the second parameter is false, then it will draw the glyphs just like mozDrawText does. If it is true, then it will add the glyphs to the current path, just like mozPathText does. This can be used to create some unique effects.

Categorias

Interwiki Language Links

{{ languages( { "en": "en/Drawing_text_using_a_canvas", "es": "es/Dibujar_texto_usando_canvas", "fr": "fr/Dessin_de_texte_avec_canvas", "ja": "ja/Drawing_text_using_a_canvas" } ) }}