Writing Text to the Canvas - HTML5 and the Canvas - HTML5, 20 Lessons to Successful Web Development (2015)

HTML5, 20 Lessons to Successful Web Development (2015)

PART II HTML5 and the Canvas

LESSON 11 Writing Text to the Canvas

Images

To view the accompanying video for this lesson, please visit mhprofessional.com/nixonhtml5/.

This lesson continues our exploration of the HTML5 canvas by looking at how you can write text to it, including using a variety of fonts and styles, as well as incorporating the various fill styles covered in the previous lesson.

Many of these examples draw on those in Lesson 10, so you may wish to refer back to that from time to time as you work your way through this one.

Writing Text

HTML 4.01 provides some handy tags for setting font sizes, colors, and faces, and CSS gives you even more control over how these are applied, including using effects such as shadowing. But when you want absolutely precise control over how your text should display, the canvas has what you need. Also, although you can use CSS to overlay text on top of a canvas, you can’t use it to layer text into a canvas, or to apply the gradient and pattern fill effects that the canvas supports.

The font Property

Let’s look at the font property first, and see how to select the font face to use. As ever, I am assuming that if you follow these examples yourself, you have also included the O() and S()functions and the code to create a 2D context on the canvas in an object with the name context. To recap, your code should look something like this:

Images

Images

The width and height of 410 by 170 pixels shown will be suitable for all the examples, and this code will create a light gray background behind the canvas so that its position and dimensions are clearly visible. You must place the O() and S() functions somewhere in your document within a <script> section for these examples to work.

So, first, let’s choose a font, like this:

context.font = ’72pt Arial’

And that’s it—when you write the text to the canvas, it will be in 72-point Arial.

Font Size Measurement Units

You can also use other measurement units for your font sizes, which can be either relative or fixed. Here’s the full list of supported relative font units:

em Ems: Based on the default preference set in the browser.

ex X-height: Based on the height of the lowercase x character.

px Pixels: Based on the resolution of the screen.

% Percentage (similar to em): Based on the default preference of the browser.

And the fixed units are:

in Inches: Imperial measurement.

cm Centimeters: Metric measurement equivalent to one 100th of a meter.

mm Millimeters: Metric measurement equivalent to one 10th of a centimeter.

pt Points: A print unit.

pc Picas: Another print unit.

Therefore the following examples are all valid:

Images

The strokeText() Function

Of course, you now need a way to write text in the newly selected font to the canvas, and you can do that using the strokeText() function, like this (which results in Figure 11-1):

context.strokeText(’Hello!’, 20, 120)

Images

FIGURE 11-1 Seventy-two-point outlined text displayed on an HTML5 canvas

And that’s how easy it is to get text onto a canvas. Simply set the font property to the font and size to use and then (for an outlined font) call strokeText(), passing the text to display and the location where the bottom-left corner of the text should appear by default, although you will see next how you can choose a different horizontal alignment with the textAlign property, and use the textBaseline property to specify the offset of the text relative to the vertical coordinate supplied.

The textAlign Property

But there’s more to writing text to a canvas than that because there are three properties you can pass values to that will further customize the way text appears. For example, using the textAlign property, you can specify the alignment of the text out of the values start, end, left, right, andcenter. So, to center some text, you could set the property like this:

Images

As you may have noticed, in order to properly center the text, the call to strokeText() needed its horizontal offset changed from 20 in the previous example to 205, because that is half the width of the canvas (which is 410 pixels wide), and the result is shown in Figure 11-2.

Images

FIGURE 11-2 The text is centered using the textAlign property

Incidentally, with the lineWidth property, you can also change the width of any line drawn using any of the line-drawing functions (more about these in Lesson 12), and this also includes strokeText(). The following line of code increases the width to five pixels, as seen in Figure 11-3, where the previous example has been modified to create a very thick border.

Images

Images

FIGURE 11-3 The border outline has been thickened to five pixels wide.

The textBaseline Property

When you draw text to the canvas, you must supply horizontal and vertical (x and y) coordinates for its top-left corner. Using the textBaseline property, you can choose the vertical offset (or y value) at which text will be displayed from this location.

top Aligns the top of the text to the y value.

middle Aligns the middle of the text to the y value.

bottom Aligns the bottom of the text to the y value.

alphabetic Aligns the alphabetic baseline of the text to the y value.

hanging Similar to top.

ideographic Similar to alphabetic.

Figure 11-4 illustrates using the first four preceding values for this property, as in the following lines of code, which write the word “top” using the textBaseline value of top. The hanging and ideographic values are offset by a tiny amount from top and alphabetic respectively—the best way to see whether you need these values is to try them for yourself.

Images

Images

FIGURE 11-4 Vertically aligning text using the textBaseline property

The fillText() Function

In the same way that you can use strokeText() in a similar fashion to strokeRect() (as detailed in the previous lesson), you can also use fillText() to create solid, gradient, and pattern-filled text, just as you can provide those types of fills to rectangles with the fillRect() function.

To show how this works, here’s some code to write the word HTML5 in a big and bold black color since no fill color has been specified (so the default of black is used), as shown in Figure 11-5:

Images

Images

FIGURE 11-5 A 116-point font filled in with the color black

Now let’s look at applying different colors, gradient fills, and patterns, starting by simply changing the text to blue, like this:

context.fillStyle = ’blue’

By now you should be so used to simple color changes that there’s no need to show the result of this in a figure. Instead let’s see how a simple vertical gradient works with the font (as shown in Figure 11-6), like this:

Images

Images

FIGURE 11-6 The solid fill has been replaced with a gradient.

Images

As explained in the previous lesson, you can set the start and end point of the gradient to any locations within (or even outside of) the canvas, allowing you to create a wider variety of effects than if they were limited to simply applying it under the object being drawn.

Using the rainbow color gradient from the previous lesson but applying it creatively as a radial gradient allows the effect of a real rainbow to be applied as the fill effect, like this, which displays as Figure 11-7:

Images

Images

FIGURE 11-7 Creating a rainbow effect with a radial gradient

In this example, a vertical offset of 230 pixels from the top of the canvas was selected. This places the center of the radial gradients at a location 60 pixels below the bottom of the canvas. This allows only a top portion of the rainbow to be used for the fill. If you select radius values of 120 pixels for the inner gradient and 240 for the outer one, the rainbow is 120 pixels wide. However, due to the way the fill works, the areas inside and outside of this section are set to the initial and final color values, so that the inside is red and the outside is violet.

If this is not the effect required, it is a simple matter to surround the initial and final colors with white (or whichever colors you prefer), and make room for them by slightly adjusting the addColorStop values of the previous start and end colors, like this:

Images

As shown in Figure 11-8, this results in only the rainbow itself being displayed.

Images

FIGURE 11-8 The inside and outside areas have been set to white.

You can also use patterns with the fillText() function, as with the following code, which attaches a function to the onload event of an image object called image that uses a marble pattern from the file marble.jpg (to ensure that the code runs only after the image has fully loaded):

Images

The image is then processed using the createPattern() function with a setting of no-repeat, and passed to a new object called pattern. In turn, pattern is supplied as the value for the fillStyle property, which is then used to fill the text using the fillText() function. The result of this can be seen in Figure 11-9.

Images

FIGURE 11-9 The text has now been filled with a pattern.

In this instance the image used for the fill pattern is larger than the canvas, so there is no need to repeat (or tile) it. But if you have a smaller image that will tile well, you can repeat it horizontally, vertically, or in both directions. See Lesson 10 for more details on how to create and use patterns.

Determining Text Width

Sometimes you need to know how wide some text will be in order to best position it. To find out this value, set all the properties as you would before writing the text and then issue statements such as the following, which creates an object called metrics into which information about the text is stored.

As illustrated by the following example (see Figure 11-10), the width property of metrics then holds the width of the text in pixels, which is displayed by the JavaScript alert() function (which pops up a small window containing the string in parentheses following the alert function name, namely some text surrounding the width property):

Images

Images

FIGURE 11-3 Displaying the width of some text

The object returned by the measureText() function currently only supports the width property.

Summary

With creating text now in your toolkit, in the following lesson we will return to looking at some of the drawing tools, this time ones that use paths to create lines, so that you have fine control over all the straight lines, shapes, and curves you could want. And in the lesson after that, I’ll show you how you can use an image as a paintbrush, how to add shadow effects, and how to manipulate each and any of the pixels (individual dots) in a canvas.

Self-Test Questions

Test how much you have learned in this lesson with these questions. If you don’t know an answer, go back and reread the relevant section until your knowledge is complete. You can find the answers in the appendix.

1. How do you choose the font for writing to a canvas?

2. With which function can you write outlined text to a canvas?

3. What are the relative measurement units supported by the canvas?

4. What are the fixed measurement units supported by the canvas?

5. Which function allows you to write filled text to a canvas?

6. How could you center-align text on a canvas?

7. Which text alignment values are supported by textAlign?

8. How can you change the horizontal line about which text will be based?

9. Which values are supported for altering this base line?

10. How can you discover the width in pixels that a text-writing call will require?