If 2D text doesn't get you jazzed, you might consider drawing 3D text instead. Although the HTML5 canvas API doesn't directly provide us with a means for creating 3D text, we can certainly create a custom draw3dText()
method using the existing API.
Follow these steps to create 3D text:
Set the canvas context and the text style:
window.onload = function(){ canvas = document.getElementById("myCanvas"); context = canvas.getContext("2d"); context.font = "40pt Calibri"; context.fillStyle = "black";
Align and draw the 3D text:
// align text horizontally center context.textAlign = "center"; // align text vertically center context.textBaseline = "middle"; draw3dText(context, "Hello 3D World!", canvas.width / 2, 120, 5); };
Define the
draw3dText()
function that draws multiple text layers and adds a shadow:function draw3dText(context, text, x, y, textDepth){ var n; // draw bottom layers for (n = 0; n < textDepth; n++) { context.fillText(text, x - n, y - n); } // draw top layer with shadow casting over // bottom layers context.fillStyle = "#5E97FF"; context.shadowColor = "black"; context.shadowBlur = 10; context.shadowOffsetX = textDepth + 2; context.shadowOffsetY = textDepth + 2; context.fillText(text, x - n, y - n); }
Embed the canvas tag inside the body of the HTML document:
<canvas id="myCanvas" width="600" height="250" style="border:1px solid black;"> </canvas>
To draw 3D text with the HTML5 canvas, we can stack multiple layers of the same text on top of one another to create the illusion of depth. In this recipe, we've set the text depth to five, which means that our custom draw3dText()
method layers five instances of "Hello 3D World!" on top of one another. We can color these layers black to create the illusion of darkness beneath our text.
Next, we can add a colored top layer to portray a forward-facing surface. Finally, we can apply a soft shadow beneath the text by setting the shadowColor
, shadowBlur
, shadowOffsetX
, and shadowOffsetY
properties of the canvas context. As we'll see in later recipes, these properties aren't limited to text and can also be applied to sub paths, paths, and shapes.