Draw 3D Text in HTML 5 Canvas and Expression Web

One of the most exciting additions to web pages by HTML5, is the Canvas element

<canvas id=”3dCanvas” width=”400″ height=”200″></canvas>

You can draw graphics such as lines, arcs, curves, circles, shapes and create nice effects etc., directly into the canvas element. In this article, I will demonstrate how to draw 3D text in HTML 5 canvas. The source code link is given at the end of this article. We will be using Expression Web (with sp2) as our web editor. Make sure that the doctype is set to HTML 5.

Step 1: HTML

Here’s the HTML needed to declare a canvas element on our page

html5-3d-canvas

Here we have added the canvas tag to the HTML code and defined the height and the width attributes with the value 200 and 400, meaning that the canvas should be 200 pixels tall and 400 pixels wide

Step 2: JavaScript Code (onload function)

Write the following JavaScript code. I will explain the code in a bit. We have also defined a drawTextInCanvas function to draw the layers and cast shadow on these layers

html5-3d-canvas-code

On the onload function(), we first retrieve the canvas object using its id attribute value (3DCanvas) in the getElementById method. This allow us to get a reference to the 2D drawing context.

Note: “3D Context” is WebGL

Next we retrieve the height and width of the canvas object. We get a reference to the 2D drawing context and store it in the ctx variable.  Once we have got a reference to the 2D context, we make a call to an HTML5 Canvas API function font, fillStyle and textAlign.

drawTextInCanvas() function

In the drawTextInCanvas function, we have used a loop to draw multiple layers of text one on top of the other, to create a 3D effect. The last parameter ‘4’ that you see in the drawTextinCanvas() function, represents the depth, where four layers are drawn one over the other.

The shadowBlur, shadowColor and shadowOffset is to apply a soft shadow beneath the text. Finally the fillText() call prints the text on the position specified and you should see the following

image

Download the 3D Text in HTML 5 and Expression Web source code

See a Live Demo

Filed Under: Expression WebHTML 5

About the Author: Minal is a freelance web and graphics designer. She specializes in designing Logos, Stationery, Graphics and Icons as well as website templates using graphical tools like Photoshop, Illustrator and Expression Web. Twitter @saffronstroke

RSSComments (0)

Trackback URL

Leave a Reply