HTML5 Game - Canvas Text alignment

Introduction

The textAlign attribute controls the horizontal positioning of text relative to a virtual vertical line running through the center of a word.

The attribute positions the text to place along the vertical center point.

The positioning options for textAlign:

  • right: The alignment line is to the right of the text.
  • end: The alignment line is to the right of the text.
  • center: The alignment line is through the center of the text.
  • left: The alignment line is to the left of the text.
  • start: The alignment line is to the left of the text.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML> <html>
<head>
 <script>
//Displays text on a canvas using various alignments.
window.onload = function()//w w w.j a  v a 2s  .co m
{
   canvas  = document.getElementById("canvasArea");
   context = canvas.getContext("2d");

   //TEXT variables.
   let xPos  = canvas.width/2;
   let yPos  = 30;

   //ATTRIBUTES.
   context.font         = "15pt Arial";
   context.fillStyle    = "black";
   context.strokeStyle  = "hotpink";
   context.lineWidth    = 1;

   //CENTERLINE.
   context.beginPath();
   context.moveTo(xPos, 0);
   context.lineTo(xPos, canvas.height);
   context.stroke();

   //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>
</head>
<body>

<div    style  = "width:200px;   height:175px;
                  margin:0 auto; padding:5px;">
<canvas id     = "canvasArea"
        width  = "200"  height = "175"
        style  = "border:2px solid black">
You're browser doesn't currently support HTML5 Canvas.
</canvas>
</div>
</body>
</html>

Related Topic