We're looking for a user researcher to understand the needs of developers and designers. Is this you or someone you know? Check out the post: https://mzl.la/2IGzdXS

Desenhando texto usando canvas

O elemento <canvas> dá suporte a desenho de texto através da API experimental Mozilla-specific.


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);


  • A fonte default é 12pt sans-serif.
  • Estas extensões de ainda não foram padronizadas pelo WHATWG.
  • You do not need a special context to use these; the 2D context works just fine.
  • All drawing is done using the current transform.
  • See bug 339553 if you'd like to read up on the implementation specifics.


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.


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);

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");

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.


Interwiki Language Links

Etiquetas do documento e contribuidores

Contribuidores para esta página: Wladimir_Palant, maicon, Verruckt, Leandro Mercês Xavier
Última atualização por: Wladimir_Palant,