HTML5 Game - Canvas Text baseline

Introduction

The textBaseline attribute controls the vertical positioning of text relative to a virtual baseline where most letters in a line of text sit.

The attribute instructs the browser what position on the text to place along the baseline.

The positioning options for textBaseline:

  • top: above the text.
  • hanging: above the text.
  • middle: through the middle of the text.
  • alphabetic: at the base of letters without a lower loop, such as the letter e.
  • ideographic: below the text, touching the bottom of characters with a descending loop, such as g.
  • bottom: below the text.

Displays text in the center of a canvas

Demo

ResultView the demo in separate window

<!DOCTYPE HTML> <html>
<head>
 <script>
// SUMMARY: Displays text in the center of a canvas.
window.onload = function()/*ww  w  .  ja  v  a  2s  .  c o  m*/
{

   canvas  = document.getElementById("canvasArea");
   context = canvas.getContext("2d");

   //TEXT variables.
   let xPos  = 75;
   let yPos  = canvas.height/2;

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

   //BASELINE.
   context.beginPath();
   context.moveTo(0,   yPos);
   context.lineTo(canvas.width, yPos);
   context.stroke();

   //TEXT BASELINE examples.
   context.textBaseline = "top";
   context.fillText("|top",         xPos*1, yPos);
   context.textBaseline = "hanging";
   context.fillText("|hanging",     xPos*2, yPos);
   context.textBaseline = "middle";
   context.fillText("|middle",      xPos*3, yPos);
   context.textBaseline = "alphabetic";
   context.fillText("|alphabetic",  xPos*4, yPos);
   context.textBaseline = "ideographic";
   context.fillText("|ideographic", xPos*5, yPos);
   context.textBaseline = "bottom";
   context.fillText("|bottom",      xPos*6, yPos);
}
</script>
</head>
<body>

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

Related Topic