Using Text on the Canvas Element: An Introduction

Kerry Butters
Kerry Butters

The canvas element, which is part of HTML5, can be used to draw 2D graphics ‘on the fly’ in supporting browsers. This includes the ability to draw a variety of shapes, such as squares, rectangles, and circles, as well as the ability to manipulate images.

What’s interesting is that you can also add text to a canvas element and this is what we’re going to be looking at today. First though, let’s have a look at some basics before we get started.

What Canvas Isn’t

Canvas is not a simple placeholder for images. Its contents are rendered using JavaScript. You can use a canvas element more than once in a document and each canvas element is then a DOM node that’s embedded that can then be used to create graphics within the canvas container.

Naturally, if you’re creating more than one canvas element on a page, you can give each canvas element a unique ID attribute so you can access each canvas element easily with JavaScript.

A basic canvas element with an ID looks like this:

<canvas id="CanvasText" width="300" height="150"></canvas>

Without CSS, a canvas element appears as a transparent rectangular box the size of which can be adjusted with the width and height attributes in the HTML and the default color when drawing on the canvas is black.

Our Page Setup

Now that we have a basic overview of the canvas element, let’s look at some HTML we can use as a basic template to do our canvas manipulation.

  <canvas id="CanvasText" width="300" height="150">
    var canvas = document.getElementByID('CanvasText');
    if (canvas.getContext) {
      var context = canvas.getContext('2d');
    // rest of the code goes here...

Note: Normally, the JavaScript you see above will be executed when we’ve ensured the DOM is ready. For brevity, we’re not including that here.

This gives us a basic, rectangular canvas at 300×150 pixels (which are the defaults, so we could omit those if we want), and the canvas will be transparent with a thin, black border.

Drawing Text with JavaScript

You can use the strokeText() or fillText() methods or a combination of the two to create the text. The first makes ‘stroked’ text with no fill and the latter creates filled text. You can also use whatever color you want and even use gradients if you really want to get creative. You will need to define font properties too, for example to set the font size.

The JavaScript to accomplish this would look something like this:

context.font = "25px Arial";
context.fillText("HTML5 Canvas Text", 10, 50);

This will produce text in Arial set at 25 pixels. The last line uses x and y coordinates (10, 50) to define where on the canvas the text will be located.

You can add color to the text like this:

context.fillStyle = "#000099";

This would produce text in a dark blue color. You can play around with the styling in the script, using a combination of fillText() and strokeText() (which adds a stroke, or border, to the text) and different colors to create various effects. You can also use bold and italics, similar to how CSS’s font shorthand property works:

context.font="italic 25px Arial";

You can alter the stroke style in order to make it heavier too; the default is 1px but this can be altered:

context.lineWidth = 2;

This is useful if you’re using larger fonts and different colors for stroke and fill to give a bit of contrast.

More Text-related Stuff

As well as using coordinates to set where your text will appear on the canvas, it’s also possible to use the textAlign property, which takes one of the following values:

  • Start
  • End
  • Left
  • Right
  • Center

So this would be defined: context.textAlign = "center"; (or left, right — whichever you want to change).

However, with respects to text, this changes the meaning of the x and y coordinates set using strokeText() and fillText(), so be aware of this as you play around with textAlign.

You can also use the textBaseline property to dictate where on the canvas text appears. Its values are:

  • Middle
  • Top
  • Bottom
  • Hanging
  • Alphabetic
  • Ideographic

And this would be used thus: context.textBaseline = "middle";.

And keep in mind that if you use this property, it will adjust the position of both the stroke and the fill — assuming you’ve declared this after the stroke and fill are defined. So you could end up with an interesting effect with the stroke offset from the fill if you adjust the textBaseline after defining the stroke but before defining the fill.

And as is done in CSS, you can add fall-back fonts in case the primary font (such as Arial used above) isn’t available on the user’s system:

context.font = "bold italic 40px Arial, Helvetica, sans serif";

Below you’ll find a basic demo incorporating some of the things we’ve discussed here:

See the Pen HTML5 Canvas Text Demo by SitePoint (@SitePoint) on CodePen.

Accessibility and Browser Support

If you are going to use the canvas element to display text, there will be accessibility challenges to overcome. It would be worthwhile to do some research in that area to ensure you’re handling this correctly.

All modern browsers support the canvas element, even going back to IE9. On IE8 and earlier, (assuming you’re not polyfilling) you can offer fallback content by putting this inside the canvas tags in the HTML. This can be a simple line of text telling the visitor that the browser doesn’t offer support, or you can use other methods to load other media.

To test a specific browser’s support of all 2D graphics related features you can use HTML5 Test which gives a score out of 555 points. For example, Firefox 27 gives a total score of 444. In the 2D graphics section, it scores 19/25, so it doesn’t support all aspects of 2D drawing, as summarized below:

  • Canvas 2D graphics: Yes
  • Text support: Yes
  • Path support: No
  • Ellipse support: No
  • Dashed line support: Yes
  • Hit testing support: No
  • Blending modes: Yes
  • PNG support: Yes
  • JPEG support: Yes
  • JPEG-XR support: No
  • WebP support: No

Again, this is only for Firefox 27; other browsers will have different results (e.g. Chrome 32 scores a 503 overall and 21/25 for the 2D Graphics features). And it’s likely you won’t need all of these features, so don’t let this stop you from using canvas in your projects.

If you’d like to know more about how to draw shapes and text using the canvas element, check out Jump Start HTML5 Canvas & SVG, on Learnable, which is one of a series that will enable you to learn HTML5 basics.

Frequently Asked Questions about Text and Canvas Element

How can I change the font size and style in the canvas text?

To change the font size and style in the canvas text, you can use the ‘font’ property of the context object. This property accepts a string value that specifies the font size in pixels and the font family. For example, context.font = “20px Arial”; will set the font size to 20 pixels and the font family to Arial. You can replace ’20px’ and ‘Arial’ with your desired font size and style respectively.

How can I align the text in the canvas?

The canvas API provides two properties to align text: ‘textAlign’ and ‘textBaseline’. The ‘textAlign’ property sets the horizontal alignment and it can be ‘start’, ‘end’, ‘left’, ‘right’, or ‘center’. The ‘textBaseline’ property sets the vertical alignment and it can be ‘top’, ‘hanging’, ‘middle’, ‘alphabetic’, ‘ideographic’, or ‘bottom’. For example, context.textAlign = ‘center’; and context.textBaseline = ‘middle’; will align the text to the center of the canvas both horizontally and vertically.

How can I add a stroke to the text in the canvas?

To add a stroke to the text, you can use the ‘strokeText()’ method of the context object. This method takes three parameters: the text string, and the x and y coordinates where the text will be placed. Before calling this method, you should set the stroke style using the ‘strokeStyle’ property and the line width using the ‘lineWidth’ property. For example, context.strokeStyle = ‘blue’; context.lineWidth = 2; context.strokeText(‘Hello World’, 50, 50); will add a blue stroke of 2 pixels width to the text ‘Hello World’.

How can I fill the text with color in the canvas?

To fill the text with color, you can use the ‘fillText()’ method of the context object. Before calling this method, you should set the fill style using the ‘fillStyle’ property. This property accepts a color value. For example, context.fillStyle = ‘red’; context.fillText(‘Hello World’, 50, 50); will fill the text ‘Hello World’ with red color.

How can I measure the width of the text in the canvas?

The canvas API provides a method called ‘measureText()’ to measure the width of the text. This method returns a TextMetrics object that contains the width of the text in pixels. For example, var metrics = context.measureText(‘Hello World’); var width = metrics.width; will store the width of the text ‘Hello World’ in the ‘width’ variable.

How can I rotate the text in the canvas?

To rotate the text, you can use the ‘rotate()’ method of the context object. This method takes one parameter: the rotation angle in radians. Before calling this method, you should translate the context to the point around which you want to rotate the text. After rotating and drawing the text, you should restore the context to its original state. For example, context.translate(x, y); context.rotate(Math.PI / 2); context.fillText(‘Hello World’, 0, 0); context.restore(); will rotate the text ‘Hello World’ 90 degrees clockwise around the point (x, y).

How can I draw multi-line text in the canvas?

To draw multi-line text, you can split the text into lines using the ‘split()’ method of the string object, and then draw each line separately with a certain line height. For example, var lines = text.split(‘\n’); for (var i = 0; i < lines.length; i++) { context.fillText(lines[i], x, y + i * lineHeight); } will draw each line of the text at a different y coordinate.

How can I add a shadow to the text in the canvas?

The canvas API provides four properties to add a shadow to the text: ‘shadowColor’, ‘shadowBlur’, ‘shadowOffsetX’, and ‘shadowOffsetY’. The ‘shadowColor’ property sets the color of the shadow, the ‘shadowBlur’ property sets the amount of blur, and the ‘shadowOffsetX’ and ‘shadowOffsetY’ properties set the distance of the shadow from the text. For example, context.shadowColor = ‘gray’; context.shadowBlur = 10; context.shadowOffsetX = 5; context.shadowOffsetY = 5; will add a gray shadow with 10 pixels blur and 5 pixels offset to the text.

How can I clear the text in the canvas?

To clear the text, you can use the ‘clearRect()’ method of the context object. This method takes four parameters: the x and y coordinates of the top-left corner of the rectangle to be cleared, and the width and height of the rectangle. For example, context.clearRect(0, 0, canvas.width, canvas.height); will clear the entire canvas.

How can I save and restore the state of the canvas?

The canvas API provides two methods to save and restore the state of the canvas: ‘save()’ and ‘restore()’. The ‘save()’ method saves the current state of the canvas, including the styles, transformations, and the clipping region. The ‘restore()’ method restores the most recently saved state. For example,; // do some drawing context.restore(); will save the state, do some drawing, and then restore the state. This is useful when you want to undo the changes made by the drawing operations.