How can I write text on a HTML5 canvas element?
Create canvas text by calling fillText()
on the CanvasRenderingContext2D
object. Set font
to define text size and style, and fillStyle
for text color. Here's a snippet to get you started:
Change up the coordinates (10, 50)
to fit the text onto the canvas wherever you like.
Finesse with text alignment
You want your text to sit pretty in horizontal and vertical alignment? Say no more. It's all about playing with textAlign
and textBaseline
:
You can also go all Picasso and rotate or scale your text giving your canvas some dynamism. Unleash your creativity!
Add a stroke to the text
If outlining your text for emphasis or style is your thing, then strokeText()
with strokeStyle
is your magic wand:
Best practices and understanding canvas measurements
- Picasso was right about the importance of setting canvas size. It ensures that your text doesn't get distorted due to scaling issues.
- Customize before you paint. Set
fillStyle
orfont
before you draw each piece of text that needs its own unique style. - Don't fret if you don't have a tape measure! Use
ctx.measureText('Your Text').width
to get the width of your text in pixels - incredibly useful for element positioning. It's all in the details.
Dynamic canvas text
Keep you canvas live and kicking by having its content update with certain events. A handy example would be a running clock:
Achieving HD text printing
For crystal clear text, you've got to cater for device pixel ratio. Here's an upgrade to your toolbox:
That slick responsive look
Ensure your canvas text moves and grooves along with the window size, because responsiveness matters:
Despite window size changes, your text will always find its center. Just like a Zen master!
Was this article helpful?