Falcon80 Logo
Aligning text on a canvas

The textAlign attibute can be used to specify how the text should be aligned on the canvas. You can align text in five ways:

start: The text begins at the location specified in the strokeText() or fillText() method

end: The text ends at the location specified in the strokeText() or fillText() method.

left: The result of using left is similar to using "start". The text is aligned to the left, with the starting point at the location specified in the strokeText() or fillText() method.

center: The centre of the text will be aligned with the location/point specified in the strokeText() or fillText() method. For eg: Suppose the text is 100 pixels wide, and you give (100,0) in the strokeText(), the text will start at (50,0) and end at (150,0).

right: This is similar to using "end". The resulting text will end at the location/point specified in the strokeText() or fillText() method.

If you do not specify alignment, the default will be 'start'.
HTML Code
<html>
<head>
  <script type="application/javascript">
function init() {
var canvas = document.getElementById("canvas");
if (canvas.getContext)
{
var ctx = canvas.getContext("2d");

// Specify the font size and font name
ctx.font = "15px verdana";

//The word "Believe" will begin at (100,20)
ctx.textAlign="start";
ctx.strokeText("Believe start", 100,20);

//The word "Believe" will end at (100,20)
ctx.textAlign="end";
ctx.strokeText("Believe end", 100,40);

//The word "Believe" will begin at (100,20)
ctx.textAlign="left";
ctx.strokeText("Believe left", 100,60);

//The word "Believe" will center at (100,20)
ctx.textAlign="center";
ctx.strokeText("Believe center", 100,80);

//The word "Believe" will begin at (100,20)
ctx.textAlign="right";
ctx.strokeText("Believe right", 100,100);

// Display the text at the specified location. In this case (5,20)
ctx.strokeText("Believe", 5,20);
}
}
  </script>
</head>
<body onload="init();">
<canvas id="canvas" width="900" height="500"></canvas><br>
</body>
</html>
 
Try Code