HTML5 Recipes : Drawing Text

The Canvas API allows us to manipulate Text in an easy manner. In this recipe we shall look at how you can literally write (or should we say draw) text on a canvas. Some approaches to drawing text are:

  • Specify the font that you wish to use by providing a value for the font attribute of the canvas context. For e.g. “32px arial”.
  • Call the strokeText(x,y,”Text to Display”) method or fillText(x,y,”Text to Display”) method on the canvas context.
  • Optionally, before you call the strokeText or fillText method, you can specify the strokeStyle, lineStyle and lineWidth attributes of the canvas context.

The code shown below is used to draw the text “HTML5” using a 64 pixels arial font and the stroke has a width of 4 and color as black.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas Line</title>
<script>
function draw_text() {

 var canvasObj = document.getElementById("mycanvas");
 var canvasCtx = canvasObj.getContext("2d");
 canvasCtx.strokeStyle = "black";
 canvasCtx.lineWidth = "4";
 canvasCtx.font = "64px arial";
 canvasCtx.strokeText("HTML5",25,50);
}

function clear_canvas() {
	var canvasObj = document.getElementById("mycanvas");
	var canvasCtx = canvasObj.getContext("2d");
	canvasCtx.clearRect(0,0,200,200);
}
</script>
</head>
<body>
<div id="instructions"><a href="#"
	onclick="draw_text();return false">Draw Text</a> <a href="#"
	onclick="clear_canvas();return false">Click to clear</a></div>
<div id="drawingsurface"><canvas id="mycanvas" width="200"
	height="200" border="1" /></div>
</body>
</html>

If you see the draw_text() method, we set the strokeStyle, lineWidth and font attributes. Then we invoke the strokeText() method. The strokeText() method only uses the stroke style and does not fill the text. See it in action here.

If we want to fill the text drawn, we can set the fillStyle, font and use the fillText() method to draw the text. See it in action here.


HTML5 Canvas Recipes

  1. Getting Started with Canvas
  2. Rectangles
  3. Strokes and Fills
  4. Drawing Text
  5. Paths
  6. Circles and Arcs
  7. Images
  8. Graphs With Canvas

Back to HTML5 Series

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s