Start learning with our library of video tutorials taught by experts. Get started

HTML5: Graphics and Animation with Canvas
Illustration by John Hersey

Rendering text


From:

HTML5: Graphics and Animation with Canvas

with Joe Marini

Video: Rendering text

One of the interesting things about canvas is that in addition to drawing shapes and curves and paths and so on, you can also draw text directly onto the canvas using a variety of text-drawing settings. In fact, drawing text is very similar to drawing any other paths. You can stroke them. You can fill them using the same fillStyle and strokeStyle as you would for other path operations and other shape operations. It's important to note that when you draw text on the canvas, it is not affected by any kind of CSS box model; it's just a path, and it's drawn using the canvas rules, not any CSS rules that you may have defined elsewhere in your document.
Expand all | Collapse all
  1. 4m 54s
    1. Welcome
      1m 3s
    2. Using the exercise files
      2m 3s
    3. Using the HTML5 Canvas element in the real world
      1m 48s
  2. 10m 31s
    1. Real-world example: CanvasMol
      2m 9s
    2. Real-world example: Raphaël-JavaScript Library
      1m 47s
    3. Real-world example: The Wilderness Downtown
      4m 1s
    4. Real-world example: Sketchpad
      1m 10s
    5. Real-world example: Pirates Love Daisies
      1m 24s
  3. 3m 28s
    1. Installing the tools
      1m 29s
    2. Exploring the Canvas examples used in this course
      1m 59s
  4. 8m 58s
    1. Introducing the Canvas tag
      6m 30s
    2. Understanding the differences between Canvas and SVG
      2m 28s
  5. 5m 36s
    1. Identifying the Canvas element's methods and properties
      1m 40s
    2. Using the Canvas drawing context
      3m 56s
  6. 43m 14s
    1. Setting and using colors and styles
      3m 19s
    2. Drawing basic shapes: Rectangles and lines
      10m 21s
    3. Understanding the Canvas state
      5m 15s
    4. Drawing complex shapes: Arcs and paths
      9m 15s
    5. Drawing complex shapes: Bézier and quadratic curves
      5m 46s
    6. Rendering text
      9m 18s
  7. 32m 35s
    1. Creating shadows
      6m 41s
    2. Drawing with patterns
      7m 20s
    3. Drawing with gradients
      6m 18s
    4. Using clipping paths
      4m 46s
    5. Drawing images and video
      7m 30s
  8. 35m 42s
    1. Transforming objects using the translate tag
      4m 18s
    2. Scaling objects with the scale transformation
      4m 7s
    3. Rotating objects with the rotate transformation
      4m 33s
    4. Applying a custom transformation
      6m 58s
    5. Compositing in Canvas using globalAlpha
      6m 36s
    6. Manipulating raw pixels
      9m 10s
  9. 41m 23s
    1. Building an image slideshow control
      4m 24s
    2. Using smooth transitions in a slideshow
      4m 28s
    3. Creating a basic animation
      5m 42s
    4. Creating animation with double buffering
      13m 13s
    5. Incorporating Canvas into a real page
      13m 36s
  10. 48s
    1. Goodbye
      48s

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
Please wait...
HTML5: Graphics and Animation with Canvas
3h 7m Intermediate Jun 03, 2011

Viewers: in countries Watching now:

One of the most exciting additions that HTML5 offers to designers is the ability to draw free-form graphics on a drawing surface known as the Canvas. In this course, author Joe Marini introduces the technical concepts behind Canvas and shows how to perform drawing operations directly in a web page. The course covers drawing basic and complex shapes, setting colors and styles, adding shadows, patterns, and gradients, more advanced techniques such as scaling, rotating, and compositing objects, and how to incorporate Canvas elements in a slideshow and an animation.

Topics include:
  • Understanding the differences between Canvas and SVG Graphics
  • Drawing shapes
  • Drawing arcs and paths
  • Rendering text
  • Using clipping paths
  • Drawing images and video
  • Transforming objects with the translate tag
  • Manipulating raw pixels
  • Applying a custom transformation
  • Creating an animation or slideshow control with Canvas
Subjects:
Developer Web Animation Web Design Web Development
Software:
HTML
Author:
Joe Marini

Rendering text

One of the interesting things about canvas is that in addition to drawing shapes and curves and paths and so on, you can also draw text directly onto the canvas using a variety of text-drawing settings. In fact, drawing text is very similar to drawing any other paths. You can stroke them. You can fill them using the same fillStyle and strokeStyle as you would for other path operations and other shape operations. It's important to note that when you draw text on the canvas, it is not affected by any kind of CSS box model; it's just a path, and it's drawn using the canvas rules, not any CSS rules that you may have defined elsewhere in your document.

And it's also important to note that you shouldn't use text on the canvas as a replacement for regular document text, because that makes accessibility really, really hard. In fact, screen readers won't be able to read the text that you draw on the canvas. So if you have any grand ideas about using canvas to replace headings, like h1s or h2s and so on, it sounds like a great idea, but you probably should find another way to do that, because accessibility-wise, that's just not going to work for people who rely on assistive technologies.

So to draw a text on the canvas, we use some text-drawing properties and methods, and those are here. So we can set a couple of properties. First, you can set the font that you want to draw with, and anything that you would normally put into a font CSS rule can go in here. And then you can also set textAlign and textBaseline. textAlign can be either a start, which is the default, which is where the drawing point starts. There's end, and there's left, right, and center. For textBaseline, there's a couple of different settings. Some of these are pretty advanced, so I'm not going to go very deep into them. There's top.

There's middle or bottom, which you may be used to from regular HTML. But there's also things like ideographic and hanging, and those are mostly used for languages such as, for example, Chinese or Korean, where there's an ideographic baseline involved with particular characters and so on. The point is that the canvas does give you that kind of control over how text is drawn. Those three properties are available for setting how text is drawn. It's very similar to how you set fillStyle or strokeStyle for strokes and fills and so on.

Then the next few routines actually draw the text. So there's the fillText method, which renders the text string supplied by the txt argument-- that's the string that you want to draw-- at the point of x and y. And then this parameter here (maxW), that's optional, which is why it's in these brackets. If you specify a maxWidth, then the canvas will render that string no wider than this space right here. So it will compress the characters if it needs to, or do what it can do to make the string fit into that space.

And along with fillText, there's strokeText. Same idea here. You give it the text to stroke, you give it the point that you want the text to be drawn at, and an optional maximum width. And the last function, measureText, will return the dimension metrics of the string that you pass in using whatever the current font settings up here that you happen to pass in. So let's take a look at some text drawing examples in real code.

Okay, so here we are in the editor, and in my Text section of my ExampleSnippets, I'm going to open up the text_start example. And we're going to go back to the Snippets, and we'll copy some code over. So the first one is the string that we're actually going to draw, and we'll copy the first example and we'll paste that in, so we'll save. So this is a really simple example. I've got a string I want to render, and I'm just going to render it using whatever the default settings are for rendering text onto the canvas.

So let's save that, and let's go ahead and look at that in the browser. And you can see that it defaults to a pretty small text size, and it draws the text right at the point where I said to draw it about 10, 20, which is right up there. So let's go back to the code and do some more advanced stuff, and let's go back to the snippets. This time, let's draw the string with some font information. So we'll place that. So now on the drawing context, I've set the font to be 25pt Georgia, and now we're going to fill the text at a different point below the first one, and we'll see what effect that had. So we'll Refresh.

So you can see that now the text is being drawn in a much bigger font and a different font face. Let's keep on going. Go back to my Snippets, and this time we're going to fill it, but we're going to use a fillStyle color. So I'll copy these lines and paste them in there and save. So now we're using a blue fillStyle to fill the text, and let's see how that works. Okay, that was pretty cool. So this time same string, only different color now.

Let's go back to the code. Okay, now let's draw the string with both a stroke and a fill. We'll copy and we'll paste. So in this case, I have defined a font of 32pt Verdana. We've got a fillStyle, we've got a strokeStyle, and in this case, the strokeStyle is green at 80% opacity, and we're going to fill and stroke the text this time.

So let's do that. Okay, a little bit different effect there. Let's uncomment this line that sets the baseline, just to show you how setting the baseline works. So we'll save, and so here's the effect. When I Refresh, you can see that the text shifted down a little bit. So let's go ahead and put that back out again and refresh, get it back to what it was. And then finally, for the last example, let's use the measureText and let's put an exclamation point in here, just to show you how this works. And we'll go down here, and we'll copy the measureText, and I'll explain this.

Now, let's go down, and I'll paste it in. So in this case, we're going to call the measureText function, and when you call measureText on theString, which in this case has been set to the text string that we're using, it's going to take the current font settings and then measure how wide the text is. There's no built-in method to measure how tall the text is, but you can fake that up pretty easily by creating a fake span and putting the text inside the span and then using the CSS features available in your browser to see how high the span is, and that will tell you how high the text is. But there's no currently built-in way of doing that.

So this is a simple example. So we're just going to calculate the width. Now I'll come back here, and actually this comes back with an object that has a width property. So then we'll call beginPath, we'll set the strokeStyle to black, and then we're going to move to a point that's underneath the text string, and then we're going to create a line that is the width of the text at the same Y point. So I'm going to underline the text, and then we call stroke to fill that line in. So let's save, and let's refresh.

And you can see that in this case, now that I've modified the string with exclamation points, the text has changed. And we now have a black line going from the part where we started drawing the text down to where the character is. You can see that there's a little bit of space left over here, and the reason for that is because actually when you call the measureText function, the measureText result that comes back is not always exactly the same size as the text string. In fact, the specification that the W3C makes states that there is currently no way of finding out what the exact bounding box of the text currently is.

That might be added to a future version of the spec, but it's not there now. So the lesson to take away from this is there's currently not a way to measure exactly how wide a string is, in order to build something, say like a text editor using the canvas. They're looking at putting that in, but it's not there right now. Anyway, in this example we've seen how to draw text on the canvas using a variety of settings, strokes, colors, and fills. We've seen how to measure the width of the text, and we've seen how to draw text using both strokes and fills.

There are currently no FAQs about HTML5: Graphics and Animation with Canvas.

Share a link to this course
Please wait... Please wait...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

join now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed HTML5: Graphics and Animation with Canvas.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Welcome to the redesigned course page.

We’ve moved some things around, and now you can



Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked