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.

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

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.

Kerry is a prolific technology writer, covering a range of subjects from design & development, SEO & social, to corporate tech & gadgets. Co-author of SitePoint’s Jump Start HTML5, Kerry also heads up digital content agency markITwrite and is an all-round geek.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.


  • Mats Svensson

    Sigh…

    I REALLY hope this won’t get popular.

    Why on earth would you publish a tutorial like this without also explaining clearly why its probably not a good idea to actually use it in most cases?

    Just saying “do some research” doesn’t cut it.
    Talk about playing with fire.

    Text rendered this way is completely F useless as text.

    If you for example want to select/highlight it to search for something ,
    or use a bookmarklet on it,
    or apply any addon-functionality at all to it.

    And when you change the text-size on the page this text doesn’t change with the rest.

    It really lack every single usefulness that you get automatically just by using normal text.

    Finally now most people seem to have understood that its BAD to use images of text instead of text,
    and then THIS happens!

    But then perhaps this will be the one that wont be miss-used at all…
    =/

    • Jingqi Xie

      It might be useful in creating decoration texts.

    • LouisLazaris

      @MatsSvensson0:disqus,

      The fact that the W3C has allowed this feature to become a standard, shows that there are use cases for it, and that it’s not impossible to make it practical and accessible. No, the post doesn’t go into details on that, but that’s a very complex subject. This is just a basic intro to text with Canvas, nothing more. The link in the article points to a Google search where you’ll see there are some articles on that subject.

      In my opinion, I agree with you, I wouldn’t touch this feature with a 10-foot pole. It seems pretty worthless when there do seem to be alternatives. But I don’t know, maybe there are use cases that I haven’t thought of yet (e.g. if you’re doing something heavy with canvas graphically, and you need some text mixed in, clearly the logical solution would be to use this rather than overlaying some regular text, which could be harder to maintain… I’m not sure.)

  • Fred Showker

    Be careful : it’s a huge bandwidth hog and in many areas will slow, stall or lock-up . . . please try to remember the rule : You know your website sucks if it takes more than 7 seconds to deliver the anticipated content!

Learn JavaScript for free!
Free course: Introduction to JavaScript

Yours when you take up a free 14-day SitePoint Premium trial.