Rendering Text with the HTML5 Canvas

Posted by dwahlin on ASP.net Weblogs See other posts from ASP.net Weblogs or by dwahlin
Published on Mon, 18 Jun 2012 19:57:52 GMT Indexed on 2012/06/18 21:17 UTC
Read the original article Hit count: 333

Filed under:
|
|
|
|

In a previous post I walked through the fundamentals of rendering shapes such as squares and circles using the HTML5 Canvas API. In this post I’ll provide a simple example of rendering and rotating text. To render text you can use the fillText() or strokeText() functions which take the text to render as well as the x and y coordinates of where to render it. To rotate text you can use the transform functions available with the HTML5 Canvas such as save(), rotate(), and restore(). To run the live demos that follow click the Result tab in the blue bar of each demo.

 

Rendering Text

This example provides a simple look at how text can be rendered using the HTML5 Canvas. It iterates through a loop, updates the text and font size dynamically, measures the width of the text using the measureText() function, and then calls fillText() to render the text with the desired font size to the screen.

 

Here’s what the code above renders:

image

 

Rotating Text

This example shows how text can be rendered and even rotated by using transform functions built into the HTML5 Canvas. The code starts by rendering text the standard way using fillText(). It then saves the state of the canvas performs an x,y coordinate transform (moves to 100, 300 respectively) and then rotates the canvas –90 degrees using the rotate() function. After the text is rendered, the canvas is reverted back to it’s existing state (saved by calling the save() function) by calling the restore() function. An additional line of text is then rendered.

 


Here’s what the code above renders:

image

 

If you’re interested in learning more about the HTML5 Canvas and how it can be used in your Web or Windows 8 applications, check out my HTML5 Canvas Fundamentals course from Pluralsight.


image

© ASP.net Weblogs or respective owner

Related posts about .NET

Related posts about canvas