Adding TEXT to Canvas

HTML 5 provides a mechanism for placing text onto the CANVAS element, but it is rendered as a graphic element, and it is not true text, and is therefor inaccessible. Any text rendered on the Canvas will need to be replicated elsewhere in the web page, outside of the Canvas element.

Writing Text to the Canvas Element

The code in our JavaScript will first declare the font size and face, followed by the coordinates on the canvas where the text will be placed.

You determine the font characteristics with the "font" attribute.

Text can be written in solid characters (filled) or outline characters (stroked). Use the "fillText" and "strokeText" attributes to specify the text that will be placed on canvas, followed by the x and y coordinates at which the text will begin.

Example code:

<script>

function init() {

// assign canvas element to "jjj"
var jjj = document.getElementById("jmecanvas").getContext('2d');
// declare fill style and font
jjj.fillStyle="rgb(200,0,0)"
jjj.font="14pt Lucida Handwriting";
jjj.fillText("Lucida Handwriting at 14 pt", 50, 50);
// filled rectangle
jjj.fillRect(25, 250, 350, 40);
// declare the stroke srtyle
jjj.strokeStyle ="rgb(0,0,50)";
jjj.lineWidth = 1;
// stroke rectangle
jjj.strokeRect(40,30,330,35);
// declare font characteristics and new text string
jjj.font="14pt Lucida Handwriting";
jjj.fillText("Lucida Handwriting at 14 pt", 50, 50);
jjj.strokeText("Stroked Lucida Handwriting", 40, 273);
}
</script>

Now let's try it out by pasting it into the <head> of our document...

Our Canvas:

An optional message or fallback measure for browsers that don't support the canvas element can be inserted immediately before the closing canvas tag. It usually says something like "Your browser doesn't support HTML5, follow this link for an old fashioned and less cool option, while your friends with a good browser enjoy this fancy CANVAS element..."

Next: Drawing Arcs and Circles on Canvas

back to Session Index...