textBaseline property

The textBaseline property specifies the vertical alignment of text drawn using the fillText or the strokeText methods. Takes one of the possible values: top, hanging, middle, alphabetic (default), ideographic, bottom (see www.w3schools.com/tags/canvas_textbaseline for meanings).asp).

Syntax

javascriptcontext.textBaseline = value;

Example

Let's set the text vertical alignment along the top line:

html<canvas id="canvas" width="200" height="200" style="background: #f4f4f4;"></canvas>
javascriptconst canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.strokeStyle = 'red';
ctx.moveTo(0, 100);
ctx.lineTo(400, 100);
ctx.stroke();
ctx.font="14px Arial";
ctx.textBaseline = 'top'; 
ctx.fillText('text', 80, 100);

Результат:

Example

Now let's set the text vertical alignment along the bottom line:

html<canvas id="canvas" width="200" height="200" style="background: #f4f4f4;"></canvas>
javascriptconst canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.strokeStyle = 'red';
ctx.moveTo(0, 100);
ctx.lineTo(400, 100);
ctx.stroke();
ctx.font="14px Arial";
ctx.textBaseline="bottom"; 
ctx.fillText('text', 80, 100); 

Результат:

See also

  • the textAlign property
    that aligns text horizontally
  • the font property
    that sets a font size and type