HTML5 Game - Drawing 3D text with shadows

Introduction

HTML5 canvas API doesn't support 3D text, we can create a custom draw3dText() method using the existing API.

Demo

ResultView the demo in separate window

<html>
    <head>
        <script>
            window.onload = function(){
                canvas = document.getElementById("myCanvas");
                context = canvas.getContext("2d");
                //from w  ww . jav  a2  s  . co  m
                context.font = "40pt Calibri";
                context.fillStyle = "black";
                // align text horizontally center
                context.textAlign = "center";
                // align text vertically center
                context.textBaseline = "middle";
                draw3dText(context, "Hello 3D World!", canvas.width / 2, 120, 5);
            };
            
            function draw3dText(context, text, x, y, textDepth){
                let 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);
            }
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Note

To draw 3D text, stack multiple layers of the same text on top of one another to create the depth.

In the code above, we've set the text depth to five.

draw3dText() method draws five instances of "Hello 3D World!" on top of one another.

Related Topic