Draw 3d text with shadows in JavaScript

Description

The following code shows how to draw 3d text with shadows.

Example


<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function(){<!--   ww  w. jav  a2 s.  c o  m-->
canvas = document.getElementById("myCanvas");
context = canvas.getContext("2d");

context.font = "40pt Calibri";
context.fillStyle = "black";
draw3dText(context, "website", 20, 120, 5);
};

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);
}
</script>
</head>
<body>
<canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
</canvas>
</body>
</html>

Click to view the demo

The code above generates the following result.

Draw 3d text with shadows in JavaScript
Home »
  Javascript Tutorial »
    Canvas »
      Canvas Text
Javascript Tutorial Canvas Text
Control text alignment vertically and horiz...
Draw 3d text with shadows in JavaScript
Draw string text on a canvas in JavaScript