Text in HTML 5 Canvas and demo

The Canvas tag as defined in the standard allows writing text, but this feature is being implemented by browsers.

Here is how looks a text in Canvas, according to an example created with online tool Logo Maker (on this site):

Text in Canvas
Demonstration with Logo Maker

It is interesting to know how writing in Canvas will works, knowing that we can use it only partially for now due the lack of compatibility.

Two methods are defined to write and they work as geometric shapes:

strokeText(texte, x, y)
Displays the contour of the text. The color depends on the strokeStyle method.
fillText(texte, x, y)
Displays a plain text. The color depends on the fillstyle method.

We will return later on this feature, when implemented on current browsers.

Some examples to check the implementation

This page is used to test the implementation of the Canvas' functions of text on a browser, with a minimalist example.

The code is not supported on Internet Explorer 8 and earlier. In this case and on all versions of browsers that do not support the tag, it is its content that is displayed, in this case the message: "Not supported!".

A text is displayed below, with a Canvas tag:

Not supported!

HTML code:

<canvas id="c1" width="400" height="100">
Not supported!
</canvas>

JavaScript code:

function canvasFun()
{
var canvas = document.getElementById('c1');
if (canvas.getContext)
{
var ctx = canvas.getContext('2d');
ctx.font = "20pt Calibri,Geneva,Arial";
ctx.strokeStyle = "rgb(0,0,0)";
ctx.fillStyle = "rgb(0,20,180)";
ctx.strokeText("Sample string", 10, 20);
ctx.fillText("Another example", 10, 60);
}
}
window.onload=canvasFun;

The text size is given by the method font.
The first string is written in an empty style with the function strokeText, the second in a common full drawing with the function fillText.

More infos and tools