JavaScript Day 21: Text on Canvas

Today we’ll take a quick look at rendering text in canvas. It’s pretty simply. There are two main functions on canvas that cause text to be drawn: fillText(text, x, y) and strokeText(text, x, y).

You pass in a string and a position and you get text. Couldn’t be simpler. As you might expect, fillText will render the text with whatever fill style you have set on the context prior to calling it, and strokeText will respect whatever stroke style you have set on the context.

Assuming by now you know how to set up your html file with a canvas and get its context, we can do something like this:

[php lang=”JavaScript”]context.fillText(“Hello BIT-101”, 50, 50);

context.fillStyle = “#ff0000”;
context.fillText(“I am red”, 50, 70);

context.lineWidth = 0.5;
context.strokeText(“Hello BIT-101”, 50, 90);[/php]

Which will give you something like this:

As you can see, the stroked text is kind of hard to make out because it is at such a small font size. Stroked text is usually better at large sizes. So we need a way to change size. We also might like to choose a different font, style, etc. These things are all done through the font property of the context. context.font takes a string which is in the same format as the font css property. Basically it’s a space separated list of descriptors of the font. Minimally you must specify a font size and family. The rest are optional. But whatever options you choose to specify, they must be in a specific order:

font-style
font-variant
font-weight
font-size/line-height
font-family

So a bare minimum font definition would look something like this:

context.font = “20pt Arial”;

If we add that line in before stroking the text, we get something that looks like this:

Much better.

Other options you’ll probably want to look at are context.textAlign and context.textBaseline, which specify how the text should be aligned horizontally and vertically in relation to the x, y point you have passed in.

This entry was posted in JavaScript. Bookmark the permalink.

One Response to JavaScript Day 21: Text on Canvas

  1. fma says:

    Is there any way, just any possible way to click on one of these particles and get something like the number of the particle?

Leave a Reply