y = sin x のグラフです。ブラウザによっては見えないかもしれません。また,W3C公認タグではないのでValidatorでエラーが出ます。仕組みはソースを見てください。
canvas要素は,Mac OS XでDashboardのために拡張されたタグで,Safari 1.3以降(iPhone/iPod touchも可),Firefox 1.5以降,Opera 9以降で実装されています。HTML 5に取り入れられることになっています。
残念ながらIE(IE 9より古いもの)はcanvasが使えません。canvasをIEのVMLでエミュレートするGoogleの Explorer Canvas は必需品です。
IE(IE 8まで)用にあらかじめ excanvas.js をどこかに置いておきます(IE以外では使われません)。
<head>
...(略)...
<!--[if lt IE 9]>
<script type="text/javascript" src="/path/to/excanvas.js"></script>
<![endif]-->
<script type="text/javascript">
function draw() {
// ...(略)...
}
</script>
</head>
<body onload="draw()">
...(略)...
<canvas id="MyCanvas" width="600" height="200"></canvas>
...(略)...
</body>
この draw() { ... } の中でcanvas要素のcontextを取得し,それに対して実際の描画を行います。
function draw() {
var canvas = document.getElementById('MyCanvas');
var context = canvas.getContext('2d');
// このcontextに対して描画する
}
例えば線分と円を描くには次のようにします。
context.beginPath(); // パスを開始 context.moveTo(20, 190); // ペンを紙に付けずに移動 context.lineTo(580, 10); // ペンを紙に付けて移動 context.stroke(); // パスに沿ってインクを流し込む(デフォルトでは1ピクセル幅) context.beginPath(); context.arc(300,100,90,0,Math.PI*2,true); // 円 context.stroke();
Last modified: 2011-09-07 13:54:00