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:
The fillText
method allows you to display a solid / filled-in version of your text instead:
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:
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:
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:
- The text you would like to display
- The horizontal (x) position
- 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:
var canvas = document.querySelector("#myCanvas");var context = canvas.getContext("2d");context.fillText("Canvas!", 40, 125);context.strokeText("Canvas!", 40, 275);
The ...