HTML5 Canvas Reference - textBaseline








The textBaseline property sets or gets the text baseline.

The options for the context.textBaseline property are as follows:

  • top - Selecting this baseline will push the text the farthest down the canvas of all the baselines.
  • hanging - It is the horizontal line from which many glyphs appear to "hang" from near the top of their face.
  • middle - The dead vertical center baseline.
  • alphabetic - The bottom of vertical writing script glyphs such as Arabic, Latin, and Hebrew.
  • ideographic - The bottom of horizontal writing script glyphs such as Han ideographs, Katakana, Hiragana, and Hangul.
  • bottom - The bottom of the em square of the font glyphs.




Browser compatibility

textBaseline Yes Yes Yes Yes Yes

JavaScript syntax

context.textBaseline='alphabetic|top|hanging|middle|ideographic|bottom';

Property Values

Values Description
alphabetic Default. Normal alphabetic baseline
top top of the em square
hanging hanging baseline
middle middle of the em square
ideographic ideographic baseline
bottom bottom of the bounding box




Example

The following code illustrates different text base line option.


<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width='500px' height='200px'/>
<script type='text/javascript'>
   canvas  = document.getElementById("canvas"); 
   context = canvas.getContext("2d");
<!--  ww w . j a va 2  s.  c o m-->
   // A2. TEXT variables.
   var xPos  = 75;
   var yPos  = canvas.height/2;

   // A3. ATTRIBUTES.
   context.font         = "10pt Arial"; 
   context.fillStyle    = "black";
   context.textAlign    = "right";
   context.strokeStyle  = "hotpink";
   context.lineWidth    = 1;
   
   // A4. BASELINE.
   context.beginPath();
   context.moveTo(0,   yPos);
   context.lineTo(canvas.width, yPos);
   context.stroke();

   // A5. 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>
</body>
</html>

The code above is rendered as follows: