2014-02-14

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:

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.

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:

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:

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:

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

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:

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

See the Pen CDJBr by Louis Lazaris (@impressivewebs) 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.

The post Using Text on the Canvas Element: An Introduction appeared first on SitePoint.

Show more