From Text to Pixels

We'll cover the following...

For getting text to appear in our canvas, we will primarily be using two methods: strokeText and fillText.

With the strokeText method, you end up drawing an outline of your text:

widget

The fillText method allows you to display a solid / filled-in version of your text instead:

widget

Now that you know this, let’s wrap up this awkward introduction and get our hands dirty with some code!

To do this, take sure you have an HTML document with a canvas element locked and loaded. If you don’t have such a document, just create a new one with the following markup:

  • HTML
html

All this sample does is give you a 550px by 350px canvas element that we will use in the next couple of sections to get our text to appear.

Using strokeText and fillText

Let’s turn all of the English words in the previous section into some sweet code that showcases what strokeText and fillText have to offer. Now, the way you use both of these methods is nearly identical:

Press + to interact
context.fillText("my text", xPosition, yPosition);
context.strokeText("my text", xPosition, yPosition);

You call them on your drawing context object, and you pass in three arguments:

  1. The text you would like to display
  2. The horizontal (x) position
  3. The vertical (y) position

There is an optional fourth argument you can specify for setting the maximum width of your text, but that’s not something you will use often. Just keep this knowledge under your hat for that rare rainy day when you’ll need it.

Getting back to our original plan, let’s add some code. Inside our script tag, go ahead and add the following lines:

Press + to interact
var canvas = document.querySelector("#myCanvas");
var context = canvas.getContext("2d");
context.fillText("Canvas!", 40, 125);
context.strokeText("Canvas!", 40, 275);

The ...