文字列を表示するには?
解説
Canvas上に文字列を表示するには、fillText()メソッドを使います。
書式は次のようになります。
context.fillText(text, x, y [, maxWidth ]);
(x,y)の位置にtextを表示します。maxWidthを指定すると、その範囲に収まるように表示されます。
同様のメソッドとして、strokeText()があります。こちらは文字の輪郭線だけを表示します。
表示位置(x,y)は、通常は文字列の左下の座標を指定しますが、
textAlignとtextBaselineプロパティの値によって意味が変わります。
textAlignプロパティは横方向の位置を指定します。次のような値を取ります。
"start" | xは文字列の始まりの位置になります(既定値) |
"end" | xは文字列の始まりの位置になります |
"left" | xは文字列の左端になります |
"center" | xは文字列の中心になります |
"right" | xは文字列の右端になります |
左から書き始める英語などの文においては、"start"と"left"は同じになります。
textBaselineプロパティは縦方向の位置を指定します。次のような値を取ります。
"top" | emスクウェアの上端 |
"hanging" | ヒンディー語など、上側に合わせる文字のベースライン |
"middle" | emスクウェアの中央 |
"alphabetic" | アルファベットのベースライン(既定値) |
"ideographic" | 漢字など表意文字のベースライン |
"bottom" | emスクウェアの下端 |
emスクウェアは、大文字のMを描画したときにできる矩形のことで、たいていの文字がこの中に納まりますが、文字やフォントによっては納まりきらない場合もあります。
表示する文字のフォントは、fontプロパティで指定できます。この値にはCSSで指定するのと同じ文字列を指定します。
以下に、fontプロパティ、textAlignプロパティ、fillText()メソッド、strokeText()メソッドの使用例を示します。
// ガイドライン
context.beginPath();
context.moveTo(100,0);
context.lineTo(100,150);
context.strokeStyle = "cyan";
context.stroke();
context.font = "16pt 'Arial'";
context.fillStyle = "red";
context.strokeStyle = "blue";
context.textAlign = "start";
context.fillText("start",100,20);
context.textAlign = "end";
context.fillText("end",100,40);
context.textAlign = "left";
context.fillText("left",100,60);
context.textAlign = "center";
context.fillText("center",100,80);
context.textAlign = "right";
context.fillText("right",100,100);
context.textAlign = "center";
context.strokeText("strokeText",100,120);
context.fillText("fillText40px",100,140,40);

以下にtextBaselineプロパティの値による違いを示します。
// ガイドライン
context.beginPath();
context.moveTo(0,80);
context.lineTo(200,80);
context.strokeStyle = "cyan";
context.stroke();
context.font = "12px sans-serif";
context.fillStyle = "blue";
context.textBaseline = "top";
context.fillText("あMg",5,80);
context.textBaseline = "hanging";
context.fillText("あMg",35,80);
context.textBaseline = "middle";
context.fillText("あMg",65,80);
context.textBaseline = "alphabetic";
context.fillText("あMg",95,80);
context.textBaseline = "ideographic";
context.fillText("あMg",125,80);
context.textBaseline = "bottom";
context.fillText("あMg",155,80);

【文字列の幅を調べる】
measureText()メソッドを使って、文字列の幅を調べることができます。
このメソッドで得られるのは、TextMetrics オブジェクトで、これは幅を表すwidthというプロパティしか持っていません。
以下に、measureText()メソッドの使用例を示します。
var s = "Weblio";
context.font = "14pt sans-serif";
var m1 = context.measureText(s);
context.fillText(s+"の幅=" + m1.width,10,40);
context.font = "10pt sans-serif";
var m2 = context.measureText(s);
context.fillText(s+"の幅=" + m2.width,10,80);

関連項目
Canvasとは