2/02/2010

テキストの色を変える(fillStyle・strokeStyle) [html5 の Canvas を使ってみる:第廿四回]

fillText();strokeText(); で書いたテキストの色を変えてみる。以前にやった fillStyle();strokeStyle(); を使ってできるみたいだ。

★html 側
<canvas id="textColor"></canvas>


★Javascript 側
onload = function() {
// 画面ロード時に描画を実行
  draw();
};
function draw() {
// id: textColor で 2 次元描画を行うことの定義
  var c = document.getElementById("textColor").getContext('2d');

// rgb で赤を指定
  c.fillStyle = "rgb(255, 0, 0)";
// 「テキストを書いてみる」という文字を、
// x:50、y:50 の座標に fillText(); で配置
  c.fillText("赤でテキストを書いてみる", 50, 50);

// rgb で青を指定
  c.strokeStyle = "rgb(0, 0, 255)";
// 「テキストを書いてみる」という文字を、
// x:50、y:100 の座標に strokeText(); で配置
  c.strokeText("青でテキストを書いてみる", 50, 100);
}


すると、こうなる。


rgb 指定ではなく、16 進数にしてみる。
// 16 進数で赤を指定
  c.fillStyle = "#ff0000";
  c.fillText("赤でテキストを書いてみる", 50, 50);

// 16 進数で青を指定
  c.strokeStyle = "#0000ff";
  c.strokeText("青でテキストを書いてみる", 50, 100);



最後に、rgba 指定にしてみる。
// rgba で赤の透明度 20% を指定
  c.fillStyle = "rgba(255, 0, 0, .2)";
  c.fillText("赤でテキストを書いてみる", 50, 50);

// rgba で青の透明度 50% を指定
  c.strokeStyle = "rgba(0, 0, 255, .5)";
  c.strokeText("青でテキストを書いてみる", 50, 100);



確認環境:
Safari 5.0、Chrome 5.0.375.70、Firefox 3.6.3、Opera 10.53

W3C;
4.8.11 The canvas element — HTML 5

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.