HTML5 キャンバス

❮ 前章へ 次章へ ❯

Your browser does not support the <canvas> element.

HTML <canvas> 要素は、web ページにグラフィックスを描画するために使用します。

左の図は、<canvas> で作成したものです。4 つの要素:赤の長方形、グラデーションの長方形、多色の長方形と 多色テキスト が描かれています。


HTML キャンバスとは?

HTML5 <canvas> 要素は、スクリプト(通常JavaScript)を通して、即座にグラフィックスを描画するために使用します。

<canvas> 要素は、グラフィックスのコンテナにすぎません。実際にグラフィックスを描画するためには、 スクリプトを使用する必要があります。

Canvas には、パス、ボックス、円、テキストの描画、および画像を描画するための複数のメソッドがあります。


ブラウザ・サポート

表中の数字は、完全に <canvas> 要素をサポートした最初のブラウザのバージョンを表しています。

要素
<canvas> 4.0 9.0 2.0 3.1 9.0

Canvas 要素

キャンバスは、HTML ページ上の矩形領域です。デフォルトでは、キャンバスにはボーダーやコンテンツがありません。

マークアップは次の通りです:

<canvas id="myCanvas" width="200" height="100"></canvas>

注:id 属性(スクリプト内で参照)と、キャンバスのサイズを定義する width と height 属性は常に指定します。 ボーダーを追加するには、style 属性を使用します。

基本的な空のキャンバスの例を次に示します:

Your browser does not support the canvas element.

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>
Try it Yourself »

線の描画

Your browser does not support the canvas element

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
Try it Yourself »

円の描画

Your browser does not support the canvas element

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
Try it Yourself »

テキストの描画

Your browser does not support the canvas element

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);
Try it Yourself »

テキストのストローク(輪郭線)

Your browser does not support the canvas element

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.strokeText("Hello World",10,50);
Try it Yourself »

線形グラデーションの描画

Your browser does not support the canvas element

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

// Create gradient
var grd = ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");

// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);
Try it Yourself »

円形グラデーションの描画

Your browser does not support the canvas element

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

// Create gradient
var grd = ctx.createRadialGradient(75,50,5,90,60,100);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");

// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);
Try it Yourself »

画像の描画

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img,10,10);
Try it Yourself »

HTML キャンバス・チュートリアル

To learn all about HTML <canvas>, Visit our full HTML Canvas Tutorial.


❮ 前章へ 次章へ ❯