HTML5 Canvas Reference - textAlign








The context.textAlign property gets and sets the horizontal alignment of the text based on its x position.

These are the available textAlign values:

  • center - The horizontal center of the text.
  • start - Text is displayed directly after the text y position.
  • end - All text is displayed before the text y position.
  • left - Text is displayed starting with the y position of the text in the leftmost position.
  • right - Text is displayed with the y position in the rightmost position of the text.




Browser compatibility

textAlign Yes Yes Yes Yes Yes

JavaScript syntax

context.textAlign='center|end|left|right|start';

Property Values

Values Description
start Default. Text is displayed directly after the text y position.
end All text is displayed before the text y position.
center The horizontal center of the text
left Text is displayed starting with the y position of the text in the leftmost position.
right Text is displayed with the y position in the rightmost position of the text.




Example

The following code sets the text alignment to center.


<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width='500px' height='200px'/>
<script type='text/javascript'>
    var context = document.getElementById("canvas").getContext("2d");
<!-- ww  w  . j a  v a  2 s.  c o  m-->
      context.font = '30pt Calibri';
      context.textAlign = 'center';
      context.fillStyle = 'red';
      context.fillText('hi', 40, 50);

</script>
</body>
</html>

The code above is rendered as follows:

Example 2

The following code compares the text alignment against canvas center.


<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width='500px' height='200px'/>
<script type='text/javascript'>
   canvas  = document.getElementById("canvas"); 
   context = canvas.getContext("2d");
<!--   w w  w  . jav  a  2 s.c  om-->
   var xPos  = canvas.width/2;
   var yPos  = 30;

   context.font         = "15pt Arial"; 
   context.fillStyle    = "black";
   context.strokeStyle  = "hotpink";
   context.lineWidth    = 1;
   
   context.beginPath();
   context.moveTo(xPos, 0);
   context.lineTo(xPos, canvas.height);
   context.stroke();

   // A5. TEXT BASELINE examples.
   context.textAlign = "right";
   context.fillText(   "right",  xPos, yPos*1); 
   context.textAlign = "end";
   context.fillText(   "end",    xPos, yPos*2);
   context.textAlign = "center";
   context.fillText(   "center", xPos, yPos*3);
   context.textAlign = "left";
   context.fillText(   "left",   xPos, yPos*4);
   context.textAlign = "start";
   context.fillText(   "start",  xPos, yPos*5);  

</script>
</body>
</html>

The code above is rendered as follows: