Draw string text on a canvas in JavaScript

Description

The following code shows how to draw string text on a canvas.

Example


<!DOCTYPE HTML>
<html>
<head>
<style>
canvas {<!--from w  ww  .  j a va  2s.  co m-->
border: thin solid black
}

body>* {
float: left;
}
</style>
</head>
<body>
<canvas id="canvas" width="850" height="840">
Your browser doesn't support the <code>canvas</code> element
</canvas>
<script>
var ctx = document.getElementById("canvas").getContext("2d");
ctx.fillStyle = "lightgrey";
ctx.strokeStyle = "black";
ctx.lineWidth = 3;
ctx.font = "100px sans-serif";
ctx.fillText("java2s.com", 50, 100);
ctx.strokeText("java2s.com", 50, 100);
</script>
</body>
</html>

Click to view the demo

The code above generates the following result.

Draw string text on a canvas 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