HTML5 Tutorial - Canvas : Text

Canvas : Text

How to display text in canvas

The magic words for printing text in canvas are "fillStyle","strokeStyle", "font","textBaseline" and lastly "fillText" and "strokeText".

<div><canvas id="c6" width="600" height = "200" style="border:solid 1px #000000;"></canvas>
<div>
<button onclick="showFillText();return true;">Fill Text</button>
<button onclick="showStrokeText();return true;">Stroke Text</button>
<button onclick="Clear_text();return true;">Erase Everything</button>
</div>
</div>

<script>
var c6 = document.getElementById("c6");
var c6_context = c6.getContext("2d");

function showFillText() {
c6_context.fillStyle = '#f00';
c6_context.font = 'italic bold 30px sans-serif';
c6_context.textBaseline = 'bottom';
c6_context.fillText('HTML5 is cool!', 50, 100);
}

function showStrokeText() {
c6_context.strokeStyle = "#003300";
c6_context.font = '40px san-serif';
c6_context.textBaseline = 'bottom';
c6_context.strokeText('HTML5 is cool?', 300, 100);
}

function Clear_text() {
c6_context.clearRect(1, 1, 600, 300);
}
</script>
Context methodDescription
fillText(text,x,y) Print the text with solid color within. Text color is determined by fillStyle().
strokeText(text,x,y) Print the text with only color the outline of the text. Text color is set by strokeStyle().
strokeStyle CSS color for text that call strokeText
fillStyle CSS color for text that call fillText
font CSS font style such as "bold, 10px, san-serif"
textBaseline This is a little bit tricky to explain. We will need another demo. The value for this propery can be "top", "hanging", "middle", "alphabetic", "ideographic" and "bottom". Default value is "alphabetic".

Below is a picture that I borrowed from WHATWG which is a perfect illustration for all kinds of text baselines. What you should observe is how a text is being placed in relation to those baselines.

Illustration of text baseline

Here I have drawn a gray line at y = 100 and I am going to place each word at y = 100 but using different "textBaseline".

c7_context.textBaseline = "top";
c7_context.fillText('Top', 5, 100);

c7_context.textBaseline = "bottom";
c7_context.fillText('Bottom', 80, 100);

c7_context.textBaseline = "middle";
c7_context.fillText('Middle', 200, 100);

c7_context.textBaseline = "alphabetic";
c7_context.fillText('Alphabetic', 300, 100);

c7_context.textBaseline = "hanging";
c7_context.fillText('Hanging', 400, 100);

If you are planning to roll out something in Canvas and you wish you could support users running on IE 8 or below, you can consider to use a free open source javascript library called ExplorerCanvas. Beware, work around is still a work around, there are some nonuniformity issues that might drive you mad.

Again, this is just a brief introduction on HTML5 Canvas, there are many more interesting features on HTML5 Canvas out there to be explored. Have fun!