After having seen how to apply styles and colors in the previous chapter, we will now have a look at how to draw text onto the canvas.
The canvas rendering context provides two methods to render text:
fillText(text, x, y [, maxWidth])
strokeText(text, x, y [, maxWidth])
fillText
exampleThe text is filled using the current fillStyle
.
function draw() { var ctx = document.getElementById('canvas').getContext('2d'); ctx.font = '48px serif'; ctx.fillText('Hello world', 10, 50); }
strokeText
exampleThe text is filled using the current strokeStyle
.
function draw() { var ctx = document.getElementById('canvas').getContext('2d'); ctx.font = '48px serif'; ctx.strokeText('Hello world', 10, 50); }
In the examples above we are already making use of the font
property to make the text a bit larger than the default size. There are some more properties which let you adjust the way the text gets displayed on the canvas:
font = value
font
property. The default font is 10px sans-serif.textAlign = value
start
, end
, left
, right
or center
. The default value is start
.textBaseline = value
top
, hanging
, middle
, alphabetic
, ideographic
, bottom
. The default value is alphabetic
.direction = value
ltr
, rtl
, inherit
. The default value is inherit
.These properties might be familiar to you, if you have worked with CSS before.
The following diagram from the WHATWG demonstrates the various baselines supported by the textBaseline
property.
Edit the code below and see your changes update live in the canvas:
ctx.font = '48px serif'; ctx.textBaseline = 'hanging'; ctx.strokeText('Hello world', 0, 100);
In the case you need to obtain more details about the text, the following method allows you to measure it.
measureText()
TextMetrics
object containing the width, in pixels, that the specified text will be when drawn in the current text style.The following code snippet shows how you can measure a text and get its width.
function draw() { var ctx = document.getElementById('canvas').getContext('2d'); var text = ctx.measureText('foo'); // TextMetrics object text.width; // 16; }
In Gecko (the rendering engine of Firefox, Firefox OS and other Mozilla based applications), some prefixed APIs were implemented in earlier versions to draw text on a canvas. These are now deprecated and removed, and are no longer guaranteed to work.
© 2005–2017 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_text