- 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.
- Big Data Analytics with Hadoop 3
- Ansible Quick Start Guide
- 實時流計算系統設計與實現
- Learning Apache Spark 2
- 腦動力:PHP函數速查效率手冊
- 大數據挑戰與NoSQL數據庫技術
- 網絡布線與小型局域網搭建
- Applied Data Visualization with R and ggplot2
- 會聲會影X4中文版從入門到精通
- INSTANT VMware vCloud Starter
- Mastering Ansible(Second Edition)
- 重估:人工智能與賦能社會
- 工業機器人入門實用教程
- Creating ELearning Games with Unity
- 常用傳感器技術及應用(第2版)