Control text alignment vertically and horizontally on HTML5 canvas in JavaScript

Description

The following code shows how to control text alignment vertically and horizontally on HTML5 canvas.

Example


<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function(){<!--  w  w w  . j ava 2  s.  com-->
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

context.font = "40pt Calibri";
context.fillStyle = "black";
// align text horizontally center
context.textAlign = "center";
// align text vertically center
context.textBaseline = "middle";
context.fillText("Hello World!", canvas.width / 2, 120);
};
</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.

Control text alignment vertically and horizontally on HTML5 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