HTML5のcanvas
同じゲームをいろんな言語で書こうとやっているGSVolley。今度はGTK+から離れてブラウザで動かすことにした。ここで使うのはHTML5で導入される描画システムのcanvas。どれぐらいのことができるのかなという興味もあってやってみる。
手順としてはHTMLファイルにcanvasタグを記入。Javascriptでcanvasに描画という流れになる。
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta http-equiv="Content-Language" content="ja" /><meta http-equiv="Content-Style-Type" content="text/css" /><meta http-equiv="Content-Script-Type" content="text/javascript" /><title>Canvas</title><script type="text/javascript" src="canvas.js"></script></head>
<body>
<h1>canvas</h1>
<canvas id="canvassample" width="640" height="400"></canvas>
</body>
</html>
HTMLファイルをこのように用意する。canvas.jsの中で描画を記述する。canvas.jsを以下のように。
onload = function() {
draw();
setInterval('animation()', 10);
};
function draw() {
var canvas = document.getElementById('canvassample');
var ctx = canvas.getContext('2d')
ctx.fillStyle = "rgb(212,212,212)";
ctx.fillRect(0,0,640,400);
ctx.fillStyle = "black";
ctx.fillRect(50,50,100,100);
ctx.beginPath();
ctx.moveTo(100,200);
ctx.lineTo(200,400);
ctx.lineTo(300,300);
ctx.closePath();
ctx.stroke();
ctx.font = "20px 'Times New Roman'";
ctx.fillText("Hello World", 240,240);
}
var x = 30;
var vx = 1;
var y = 50;
var vy = 1;
function animation() {
var canvas = document.getElementById('canvassample');
var ctx = canvas.getContext('2d')
ctx.save();
ctx.fillStyle = "rgba(200,0,0,0.5)";
ctx.strokeStyle = "green";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(x,y, 12, 0, Math.PI * 2);
ctx.closePath();
ctx.stroke();
ctx.fill();
ctx.restore();
if ( x > 640) {
vx = -1 ;
} else if ( x < 0 ) {
vx = 1;
}
if ( y > 400) {
vy = -1 ;
} else if ( y < 0 ) {
vy = 1;
}
x += vx;
y += vy;
}
何やら描画されて円が動きまわっていれば正常である。動作確認はChrome15で行なっている。
canvasのcontextを生成してあとは描画命令を書くだけ。ここらあたりは他のツールキット等と感覚は変わらない。アニメーションがしたい場合はsetIntervalで定期的に呼び出す関数を指定すればよい。癖があるなと思うのがプロパティの設定などが文字列で行うあたり。

Debian QA
Facebook (taniguchi.takaki)
Twitter (@takaki_t)