textBaselineプロパティ

textBaselineプロパティは、 メソッド fillText またはメソッド strokeText を使用して描画されたテキストの垂直方向の配置を設定します。 取り得る値のいずれか一つを受け入れます: top, hanging, middle, alphabetic (デフォルト), ideographic, bottom (値の理解については www.w3schools.com/tags/canvas_textbaseline.aspを参照)。

構文

javascriptコンテキスト.textBaseline = 値;

例

テキストの垂直方向の配置を 上端基準に設定してみましょう:

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);

Результат:

例

次に、テキストの垂直方向の配置を 下端基準に設定してみましょう:

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); 

Результат:

関連項目

  • 水平方向のテキスト配置を行う プロパティ textAlign
  • フォントのサイズと種類を設定する プロパティ font