官术网_书友最值得收藏!

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.

Drawing 3D text with shadows

How to do it...

Follow these steps to create 3D text:

  1. 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";
  2. 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);
    };
  3. 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);
    }
  4. 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.

主站蜘蛛池模板: 涞水县| 乐安县| 静宁县| 博客| 剑河县| 左贡县| 丹棱县| 佛冈县| 治县。| 靖安县| 樟树市| 甘孜| 横峰县| 天柱县| 曲麻莱县| 祁门县| 马鞍山市| 新疆| 右玉县| 扶风县| 通州区| 临颍县| 望谟县| 临潭县| 九龙城区| 晋江市| 泸溪县| 应城市| 临湘市| 宁陵县| 赣榆县| 神木县| 温宿县| 晴隆县| 武平县| 克什克腾旗| 柳河县| 育儿| 阿克苏市| 和林格尔县| 社会|