canvasに文字列を書く:JavaScriptメモ
メモです
canvasで文字列を表示
canvasに文字を書くテスト(IEは9以上、その他HTML5対応ブラウザ)
当初canvasには文字列表示のAPIがなく、HTMLのDOMでdiv制御を行う等の それはそれは汚らしい作業をしなければ文字を重ねることができませんでした。
現在ではfillText(文字列、x位置、y位置)というAPIが用意され、文字列の 表示もできるようになっています。
残念ながらIE8までcanvas表示に活躍したexcanvas.jsでは対応されないようです。
この記事のサンプルはIE9以上かfirefox,GoogleChrome,Opera,Safariなどの HTML5対応をうたっているブラウザでのみ動作します。
次のコードでcanvas上の計算で得た位置に文字を出力しています。
<center><!-- centerは不滅です -->
<p>
canvasに文字を書くテスト(IEは9以上、その他HTML5対応ブラウザ)
</p>
<p>
<canvas id="canvas1" width="480" height="400" ></canvas>
</p>
</center>
<script type="text/javascript">
var names=["東京","名古屋","大阪","京都","高知","神戸","横浜"
,"福岡","札幌","New York","London","Paris","Salzburg"];
var ring ={x:240,y:200,radius:170};
var block={width:80,height:30};
function draw(){
var n= Math.floor(Math.random()*(names.length-2)+2);
var s= Math.floor(Math.random()*names.length%n);
var canvas = document.getElementById('canvas1');
var context= canvas.getContext('2d');
context.save(); // おまじない
context.clearRect(0,0,canvas.width,canvas.height);
context.beginPath();
context.arc(ring.x, ring.y, 170, 0, Math.PI*2, false);
context.lineWidth=4;
context.strokeStyle = 'blue';
context.stroke();
context.lineWidth=1;
context.strokeStyle = 'black';
for(var i=0;i<n;++i){
var nidx= (s+i+names.length)%names.length;
var r= Math.PI*2/n*i;
var x= Math.cos(r);
var y= Math.sin(r);
context.beginPath();
context.rect(ring.x-ring.radius*x-block.width/2
,ring.y-ring.radius*y-block.height/2
,block.width,block.height);
if( nidx==0 ) context.fillStyle = 'lightgreen';
else context.fillStyle = 'yellow';
context.fill();
context.stroke();
context.beginPath();
if( nidx==4 ) context.fillStyle = 'red'; // 文字の色
else context.fillStyle = 'black';
context.font = "12px arial"; // フォント
context.textAlign = "center";
context.fillText(names[nidx]
,ring.x-ring.radius*x
,ring.y-ring.radius*y+4);
}
context.restore(); // おまじない
}
function start(){
draw();
setInterval(draw,3000);
}
try{ // load完了で関数呼び出し
window.addEventListener("load",start,false);
}
catch(e){
wi
</script>
fillStyle属性で文字の色を変えられます。strokeStyleでは ないことに注意が必要です。
font属性にフォント情報を入れ、サイズなどを指定できます。
textAlign属性に"center"を 設定するとセンタリングできます。fillTextで指定するx値を中心として描画されます。
fillText関数で文字列を指定位置に表示できます。
contextのsave(),restore()はこのプログラムでは不要ですが、思わぬ副作用を 防ぐため、習慣づけることをお勧めします。
ほぼ同じ構成でcanvasの文字列の代わりにDOMでHTMLの<A>タグを置くサンプルを canvas上にHTML要素を置く:メモに置いてあります。
IE9に関する補足
IE9でcanvasを使用するためには、現在次のおまじないを唱える必要があります。
<!-- saved from url=(0014)about:internet --> <meta http-equiv="X-UA-Compatible" content="IE=edge">
| 固定リンク

