テキストを描画するには, fillTextメソッド, または, strokeTextメソッドを利用します.
それぞれ, テキストの塗りつぶし, 輪郭描画を実行します.
引数の設定はどちらのメソッドも同じで, 第1引数に描画するテキスト, 第2, 3引数にx座標, y座標を指定します.
そして, fontプロパティに文字列を設定することで, フォントやフォントサイズを変更可能です.
また, パスの描画と同様にfillStyle / strokeStyleプロパティで色を変更できます.
さらに, strokeTextメソッドであれば, lineWidthプロパティの設定も有効です.
サンプルコード 11
/*
* Add code to sample code 01
*/
// ....
// Change style
context.strokeStyle = 'rgba(255, 0, 0, 1.0)'; // = 'red', '#ff0000', 'hsla(0, 100%, 50%, 1.0)'
context.lineWidth = 3;
context.fillStyle = 'rgba(0, 0, 255, 1.0)'; // = 'blue', '#0000ff', 'hsla(240, 100%, 50%, 1.0)'
context.font = '36px "Times New Roman"';
var x = canvas.width / 2;
var y = canvas.height / 2;
context.strokeText('Canvas', x, y);
context.fillText('Canvas', x, y);
ところで, サンプルコード 11は中心にテキストを描画したいのですが, 実際にはそのようになりません.
その理由は, 中心からテキストが描画されるからです.
そこで, テキストのサイズを測定して, その値を基に座標をずらして描画すれば, センタリングできそうです.
measureTextメソッドを利用することによって, それを実現できます..
このメソッドの引数にサイズを測定したいテキストを指定します.
メソッドの戻り値として, TextMetricsオブジェクトを取得できます.
そして, TextMetricsオブジェクトのwidthプロパティにアクセスすることで, テキストの幅を取得可能です.
measureTextメソッドでテキストの高さは取得できません.
そこで, テキストの高さはfontプロパティに設定しているフォントサイズから取得します (ただし, 正確な高さではありません).
サンプルコード 12
/*
* Add code to sample code 01
*/
// ....
var text = 'Canvas';
// Change style
context.strokeStyle = 'rgba(255, 0, 0, 1.0)'; // = 'red', '#ff0000', 'hsla(0, 100%, 50%, 1.0)'
context.lineWidth = 3;
context.fillStyle = 'rgba(0, 0, 255, 1.0)'; // = 'blue', '#0000ff', 'hsla(240, 100%, 50%, 1.0)'
context.font = '36px "Times New Roman"';
var x = canvas.width / 2;
var y = canvas.height / 2;
// for centering text
var textMetrics = context.measureText(text);
var offsetX = textMetrics.width / 2;
var offsetY = Math.floor(parseInt(context.font.match(/\s*(\d+)px.*/)[1]) / 4);
context.strokeText(text, (x - offsetX), (y + offsetY));
context.fillText(text, (x - offsetX), (y + offsetY));
実は, 横方向のセンタリングはより簡単な方法があり, textAlignプロパティに 'center' を指定することです.
状況によってはテキストの幅を取得したい場合もあると思います.
そんなに難しいことではないので, どちらの方法も習得しておくと役に立つはずです.
サンプルコード 13
/*
* Add code to sample code 01
*/
// ....
var text = 'Canvas';
// Change style
context.strokeStyle = 'rgba(255, 0, 0, 1.0)'; // = 'red', '#ff0000', 'hsla(0, 100%, 50%, 1.0)'
context.lineWidth = 3;
context.fillStyle = 'rgba(0, 0, 255, 1.0)'; // = 'blue', '#0000ff', 'hsla(240, 100%, 50%, 1.0)'
context.font = '36px "Times New Roman"';
var x = canvas.width / 2;
var y = canvas.height / 2;
// for centering text
context.textAlign = 'center';
var offsetY = Math.floor(parseInt(context.font.match(/\s*(\d+)px.*/)[1]) / 4);
context.strokeText(text, x, (y + offsetY));
context.fillText(text, x, (y + offsetY));