textAlign プロパティ
構文
- context .
textAlign[ = value ] -
現在のテキストのアラインメント設定を返します。
値をセットして、アラインメントを変更することができます。その値には、
start,end,left,right,centerが利用可能です。デフォルトはstartです。それ以外の値は無視されます。
仕様
textAlign IDL 属性は、取得時においては、現在の値を返さなければいけません。セット時においては、この値に start, end, left, right, center のいずれかをセットすれば、新たな値に変更されなければいけません。そうでなければ、新しい値は無視されなければいけません。コンテキストが生成されると、textAlign 属性は start で初期化されなければいけません。
※ 原文:http://www.w3.org/TR/2010/WD-2dcontext-20100624/#dom-context-2d-textalign
サンプル
このサンプルは、上から順に、Canvas の textAlign 属性に "start", "end", "left", "right", "center" を指定しながら文字列を描画したものです。それぞれの文字列のアンカーポイント(fillText メソッドに指定する座標)には赤丸を描きました。
ご覧のように、 英語や日本語のように、文字を左から右へ読む言語の場合、canvas 要素のスタイルに directionプロパティーがセットされていなければ、Canvas の textAlign 属性の値が "start" と "left" の結果は同じになります。 同様に、Canvas の textAlign 属性の値が "end" と "right" の結果も同じになります。
しかし、"start" と "left" 、そして、"end" と "right" が Canvas 内で同じに解釈されているわけではありません。たまたま、文字を左から右へ読む言語だったため、結果が同じになったに過ぎません。"start" とはアンカーポイントから「言語の読む向き」に向かって文字列を描画するのに対し、"left" は「言語の読む向き」にかかわらず強制的にアンカーポイントを基準に左寄せで(アンカーポイントの右側に)文字列を描画します。これを実際に試してみましょう。
canvas 要素のスタイルで direction プロパティーに "rtl" を、unicode-bidi プロパティーに "bidi-override" をセットすると、Canvas 内に描画される文字は強制的に右から左へ描画されます。
<canvas id="c2" width="150" height="200" style="direction:rtl;unicode-bidi:bidi-override;"></canvas>
前述のサンプルと同じコードを使って試した結果は数の通りです。
Canvas の textAlign 属性の値が "start", "end" の場合は、文字列の描画位置が、前述の「文字が左から右へ行く」場合と反対になります。
/* フォントの種類とサイズをセット */ ctx.font = "20px 'Courier New'"; /* textAlignにstartをセット */ ctx.fillStyle = "black"; ctx.textAlign = "start"; ctx.fillText("start", 75, 30); /* 補助点 */ ctx.fillStyle = "red"; ctx.beginPath(); ctx.arc(75, 30, 3, 0, Math.PI*2, false); ctx.fill(); /* textAlignにendをセット */ ctx.fillStyle = "black"; ctx.textAlign = "end"; ctx.fillText("end", 75, 70); /* 補助点 */ ctx.fillStyle = "red"; ctx.beginPath(); ctx.arc(75, 70, 3, 0, Math.PI*2, false); ctx.fill(); /* textAlignにleftをセット */ ctx.fillStyle = "black"; ctx.textAlign = "left"; ctx.fillText("left", 75, 110); /* 補助点 */ ctx.fillStyle = "red"; ctx.beginPath(); ctx.arc(75, 110, 3, 0, Math.PI*2, false); ctx.fill(); /* textAlignにrightをセット */ ctx.fillStyle = "black"; ctx.textAlign = "right"; ctx.fillText("right", 75, 150); /* 補助点 */ ctx.fillStyle = "red"; ctx.beginPath(); ctx.arc(75, 150, 3, 0, Math.PI*2, false); ctx.fill(); /* textAlignにcenterをセット */ ctx.fillStyle = "black"; ctx.textAlign = "center"; ctx.fillText("center", 75, 190); /* 補助点 */ ctx.fillStyle = "red"; ctx.beginPath(); ctx.arc(75, 190, 3, 0, Math.PI*2, false); ctx.fill();
ブラウザ対応状況
| Firefox | Safari | Chrome | Opera | IE | ExplorerCanvas |
|---|---|---|---|---|---|
| 2 × | 2 × | 1 × | 9.2 × | 9 ○ | 0002 × |
| 3 × | 3 × | 2 ○ | 9.5 × | 3 × | |
| 3.5 △ | 4 ○ | 3 ○ | 10 × | ||
| 3.6 △ | 5 ○ | 6 ○ | 10.60 ○ |
最新のブラウザーすべてで textAlign がサポートされています。ただし、Firefox と Opear は、CSS の direction プロパティ に対応していないため、上記サンプルは期待通りの結果になりません。