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

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.

主站蜘蛛池模板: 安福县| 克什克腾旗| 专栏| 芜湖县| 金门县| 收藏| 北宁市| 兴化市| 博乐市| 遵化市| 绩溪县| 郓城县| 大悟县| 军事| 遂川县| 渝北区| 山西省| 嘉峪关市| 南皮县| 明水县| 广灵县| 青河县| 内江市| 余干县| 岗巴县| 张掖市| 谷城县| 山东省| 仙居县| 泰安市| 青州市| 天峨县| 富裕县| 北宁市| 邛崃市| 鸡西市| 莱州市| 林周县| 沙田区| 叶城县| 自贡市|