12/19/2009

線に色を塗る(strokeStyle) [html5 の Canvas を使ってみる:第八回]

描いた線や図形の枠に色で塗ってみる。

今回は arc(); での円と rect(); での矩形も仲間に入れてみた。3 つの図形を判りやすいように、c1・c2・c3 と便宜上分けた。

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


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

// 三角形を lineTo();closePath(); で描画
  c1.beginPath();
  c1.moveTo(0, 30);
  c1.lineTo(100, 60);
  c1.lineTo(20, 70);
  c1.closePath();
// 線の色を rgb(255, 0, 0) の赤で指定
  c1.strokeStyle = "rgb(255, 0, 0)";
// これらの座標に対して線を引く指令
  c1.stroke();

// id: fillStyle で 2 次元描画を行うことの定義(2 つめ)
  var c2 = document.getElementById("fillStyle").getContext('2d');

// 重ねる円を arc(); で描画
  c2.beginPath();
  c2.arc(80, 60, 50, 0, (360 * Math.PI / 180), false);
// 線の色を rgb(0, 0, 255) の青で指定
  c2.strokeStyle = "rgb(0, 0, 255)";
// これらの座標に対して線を引く指令
  c2.stroke();

// id: fillStyle で 2 次元描画を行うことの定義(3 つめ)
  var c3 = document.getElementById("fillStyle").getContext('2d');

// 重ねる四角形を rect(); で描画
  c3.beginPath();
  c3.rect(60, 30, 50, 50);
// 線の色を rgb(0, 255, 0) の緑で指定
  c3.strokeStyle = "rgb(0, 255, 0)";
// これらの座標に対して線を引く指令
  c3.stroke();
}


すると、こうなる。


で、fillStyle と同様に、色の値は CSS のフォーマットで指定するので、rgba を用いて、半透明にすることもできる。ここでは、赤い三角の色を 30% に、青い丸の色を 50% に、緑の四角の色を 20% にしてみる。
  c1.strokeStyle = "rgba(255, 0, 0, .3)";
  c2.strokeStyle = "rgba(0, 0, 255, .5)";
  c3.strokeStyle = "rgba(0, 255, 0, .2)";



これも transparent を指定すれば、透明になる。が、塗りつぶしなしで線に transparent 指定をしてしまうと、当たり前だが描画されなくなってしまうので、fillStyle で rgba(0, 0, 255, .1) で 10% だけ青を塗り、判りやすくしてみる。
  c2.strokeStyle = "transparent";
  c2.fillStyle = "rgba(0, 0, 255, .1)";
  c2.fill();



もちろん 16 進数でも可能。
  c1.strokeStyle = "#ff0000";
  c2.strokeStyle = "#0000ff";
  c3.strokeStyle = "#00ff00";



確認環境:
Safari 5.0、Firefox 3.6.3、Chrome 5.0.375.70、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.