Drawing Text on HTML5 Canvas

draw text on canvas

Writing Text on canvas is pretty straightforward. All we need to know about is certain properties and methods that are pre-defined on the canvas’s context. You can draw/write all unicode characters using the related methods.

Getting Started

As usual, first you would get the 2d context.

var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');

font

The font property accepts a string that uses the same syntax as the CSS font property. Default is 10px sans-serif.

ctx.font = 'italic 40px Verdana';

fillText()

The fillText method draws the text based on the values of the font, textAlign and textBaseline properties. The text is filled using the color specified for fillStyle.

It accepts 4 arguments:

  • Text to draw
  • X coordinate to start
  • Y coordinate to start
  • (optional) Max Width – If it is less than the computed width of the string, then the string is condensed horizontally or a smaller font is used.
ctx.fillText('Hello World', 0, 40);

Similarly, there’s also strokeText that strokes the text instead of drawing/filling it. The color used is the one specified for strokeStyle property.

textAlign

The textAlign property defines the alignment of the text. Some possible values it accepts are left, right, center, start and end. The start value specifies left alignment for left-to-right locales and right aligned for right-to-left locales, while the end value specifies right alignment for left-to-right locales and left alignment for right-to-left locales.

Default is start.

textBaseline

This property accepts a string defining the text baseline. Possible values are top, middle, alphabetic and bottom.

Default is alphabetic.

Demo

It always feels great to look at demos.




			

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>