| 項目 | 説明 |
|---|---|
| 形式 | <canvas>〜</canvas> |
| サポート | H5+ / e9+ / Fx1.5+ / Op9+ / Ch1+ / Sa3 |
| タグの省略 | 開始タグ:必須、終了タグ:必須 |
| 包含可能要素 | ブロック要素 / インライン要素 |
canvas は HTML5 の新要素で、図形を描画するためのキャンバスをサポートします。<canvas>〜</canvas> で用意した矩形領域に JavaScript を用いて線や画像を表示します。
現時点(2011年5月)では、IE9以降、Firefox 1.5以降、Opera 9以降、Safari 1.3以降が 平面(2D)コンテキストをサポートしています。
Google が公開した JavaScriptライブラリ 「Explorer Canvas」を用いることで、IE6/IE7/IE8 でも canvas を VML でシミュレートできます。ブラウザ利用者がプラグインなどをインストールしておく必要は無く、Web製作者側が、JavaScript のライブラリをひとつ読み込ませるだけで実現可能です。多少の制限はあるそうですが、かなり使い物になりそうです。
| 属性 | 意味 |
|---|---|
| width=n | H5+。横幅を指定します。 |
| height=n | H5+。縦幅を指定します。 |
| 属性 | 意味 |
|---|---|
| class=class | H5+。クラスを指定します。 |
| id=id | H5+。IDを指定します。 |
| style=style | H5+。スタイルシートを指定します。 |
| title=title | H5+。タイトルを指定します。 |
| dir=dir | H5+。文字の表示方向を指定します。 |
| lang=lang | H5+。言語を指定します。 |
| accesskey=key | H5+。アクセスキーを指定します。 |
| tabindex=n | H5+。タブインデックスを指定します。 |
| contenteditable=bool | H5+。要素を編集可能にします。 |
| contextmenu=id | H5+。コンテキストメニューを指定します。 |
| draggable=bool | H5+。ドラッグを可能にします。 |
| dropzone=value | H5+。ドロップを可能にします。 |
| hidden | H5+。要素を非表示にします。 |
| spellcheck=bool | H5+。スペルをチェックします。 |
| HTMLソース |
|---|
<html>
<head>
<title>CANVAS TEST</title>
<!--[if lt IE 9]> // Explorer Canvasを読み込む
<script type="text/javascript" src="lib/excanvas.js"></script>
<![endif]-->
<script type="text/javascript">
<!--
window.onload = function() {
var cv = document.getElementById('cv1'); // 要素を得る
if (!cv) { return; }
var ct = cv.getContext('2d'); // 2D(平面)コンテキストを得る
if (!ct) { return; }
ct.fillStyle = '#ffeeee';
ct.fillRect(0, 0, cv.width, cv.height); // 矩形を塗りつぶす
ct.strokeStyle = '#ff0000';
ct.strokeRect(0, 0, cv.width, cv.height); // 矩形を描画する
ct.beginPath();
ct.strokeStyle = '#ff0000';
ct.arc(70, 50, 40, 0, Math.PI * 2, false); // 円を描画する
ct.stroke();
ct.beginPath();
ct.strokeStyle = '#0000ff';
ct.moveTo(0, 0);
ct.lineTo(140, 100); // 線を描画する
ct.stroke();
}
// -->
</script>
</head>
<body>
<canvas id="cv1" width="140" height="100"></canvas>
</body>
</html>
|
| ブラウザ表示例 |
|---|
|
|
// キャンバス要素を得る
cv = document.getElementById(id);
// 2Dコンテキストを得る
ct = cv.getContext('2d');
// 描画を開始する
ct.beginPath();
// 描画した結果を表示する
ct.stroke();
// 線の色を設定する
ct.strokeStyle = '#ff0000';
// 塗りつぶしの色を設定する
ct.fillStyle = '#ff0000';
// ペンの位置を移動させる
ct.moveTo(x, y);
// 現在のペン位置を起点に線をひく
ct.lineTo(x, y);
// 矩形を描画する (beginPath()/stroke()は不要)
ct.strokeRect(x, y, w, h);
// 矩形を塗り潰す (beginPath()/stroke()は不要)
ct.fillRect(x, y, w, h);