- HTML5 Canvas Cookbook
- Eric Rowell
- 278字
- 2021-08-27 12:08:05
Drawing 3D text with shadows
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.

How to do it...
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>
How it works...
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.
- 網(wǎng)上沖浪
- 來吧!帶你玩轉(zhuǎn)Excel VBA
- 計(jì)算機(jī)圖形圖像處理:Photoshop CS3
- 計(jì)算機(jī)系統(tǒng)結(jié)構(gòu)
- 悟透AutoCAD 2009案例自學(xué)手冊(cè)
- 計(jì)算機(jī)組網(wǎng)技術(shù)
- 在實(shí)戰(zhàn)中成長:C++開發(fā)之路
- 網(wǎng)絡(luò)脆弱性掃描產(chǎn)品原理及應(yīng)用
- 設(shè)計(jì)模式
- 計(jì)算機(jī)應(yīng)用基礎(chǔ)學(xué)習(xí)指導(dǎo)與練習(xí)(Windows XP+Office 2003)
- 軟件質(zhì)量管理實(shí)踐
- 工程地質(zhì)地學(xué)信息遙感自動(dòng)提取技術(shù)
- 巧學(xué)活用AutoCAD
- Proteus從入門到精通100例
- Photoshop CS6婚紗數(shù)碼照片處理達(dá)人秘笈