HTML5 2

Canvas

Canvasの様々な機能を紹介します。

パスによる描画

パスによって、直線・曲線を描くことができます。

<canvas id = "canvas1" width = 300 height = 300></canvas>
<script>
var canvas1 = document.getElementById("canvas1");
var context1 = canvas1.getContext("2d");

context1.beginPath();
context1.moveTo(0, 0);
context1.lineTo(100, 100);
context1.stroke();

context1.strokeStyle = "rgb(255, 0, 0)";
context1.beginPath();
context1.moveTo(0, 100);
context1.quadraticCurveTo(50, 200, 100, 100);
context1.stroke();

context1.strokeStyle = "rgb(0, 255, 0)";
context1.beginPath();
context1.moveTo(0, 200);
context1.bezierCurveTo(0, 300, 100, 200, 100, 300);
context1.stroke();

context1.strokeStyle = "rgb(0, 0, 255)";
context1.beginPath();
context1.moveTo(100, 100);
context1.arcTo(125, 25, 200, 100, 25);
context1.stroke();
</script>

図形がパス内にあるかどうか

ある図形がパスの中にあるかどうかは、コンテキストのisPointInPathメソッドで調べることができます。

<canvas id = "canvas20" width = 300 height = 300></canvas>
<script>
var canvas20 = document.getElementById("canvas20");
var context20 = canvas20.getContext("2d");

context20.beginPath();
context20.arc(100, 100, 60, 0, Math.PI*2, false);
context20.stroke();

for(var i = 0; i < 20; i++) {
	if(context20.isPointInPath(10*i, 10*i))
		context20.fillStyle = "rgb(255, 0, 0)";
	else
		context20.fillStyle = "rgb(0, 0, 255)";
	context20.fillRect(10*i, 10*i, 10, 10);
}
</script>

影のつけ方

影は、コンテキストの以下のプロパティでつけることができます。

shadowOffsetX
影の水平方向のオフセット値
shadowOffsetY
影の垂直方向のオフセット値
shadowColor
影の色
shadowBlur
影のぼかし幅
<canvas id = "canvas2" width = 200 height = 200></canvas>
<script>
var canvas2 = document.getElementById("canvas2");
var context2 = canvas2.getContext("2d");

context2.shadowOffsetX = 7;
context2.shadowOffsetY = 7;
context2.shadowColor = "rgb(50, 50, 50)";
context2.shadowBlur = 7;
context2.fillStyle = "rgb(255, 0, 0)";
context2.fillRect(10, 10, 100, 100);
</script>

描画が重なったときの処理

図形が重なっている場合には、 コンテキストのglobalCompositeOperationプロパティに代入した指定に従って描画されます。

<canvas id = "canvas3" width = 200 height = 200></canvas>
<script>
var canvas3 = document.getElementById("canvas3");
var context3 = canvas3.getContext("2d");

context3.fillStyle = "green";
context3.fillRect(10, 10, 100, 100);

context3.globalCompositeOperation = "source-over";

context3.beginPath();
context3.fillStyle = "blue";
context3.arc(100, 100, 60, 0, Math.PI*2, false);
context3.fill();

context3.globalCompositeOperation = "source-over";
context3.strokeStyle = "rgb(150, 150, 150)";
context3.strokeRect(10, 10, 100, 100);
context3.beginPath();
context3.arc(100, 100, 60, 0, Math.PI*2, false);
context3.stroke();
</script>

globalCompositeOperationの値は、以下の通りです。


Prev | Next
index | home
abetmhr@gmail.com