Friday, 20 May 2011

How to Draw Text On My Simple Html5 Canvas Drawing Board Demo App


One more option has just been added to the drawing tools in my Html5 canvas drawing board demo application: text.  Now you can easily type text in a box, select a font, a size for your text, and a color, then click on the board and the text gets immediately drawn on the canvas.  Cool!  Here's the little function that does the trick


The Text Tool


When you select a drawing tool you're now presented with a new one that's just been added to the list, the Text tool. It's in fact possible to draw text on an HTML5 canvas application, and it's rather easy to do, as you'll see.

Apart from little bits of code that mainly add a couple of variables to hold text-related data and bind event handlers to the various events, i.e., code that makes things happen when events like the page loading or an option getting clicked, etc., take place, the key function that makes possible the text functionality is the following:

function drawText(sampleText, x, y)
{
context.fillStyle = curColor;
context.lineWidth = lineWidth;
context.font = curFontSize + ' ' + curFont;
context.fillText(sampleText, x, y);
} //end of drawText() function

When this function gets called, you need to provide the text to be drawn on the canvas and the x and y coordinates, which in this case will be the position of the mouse as it clicks the drawing board. The text is taken from a text box: the user simply types whatever she likes into the box and that's what gets displayed on the drawing board. Inside this function the HTML5 canvas API method fillText() is called and the magic of making the text appear at the click of the mouse just happens!

Demos


Here are, as usual, the URLs of the latest live demo and downloadable code to the demo application.

Let me know how you've used all the great features of HTML5 canvas, I'm really curious to hear from you!

0 comments:

Post a Comment