Canvasを使う

本屋などにいくとhtml5でつくるゲームとかの本が結構あるので、少し触ってみた。ほとんど詳しくないので基礎的なことしかできなかった。とりあえず、キャンバスの背景設定と図形を書いて、定期的に移動するようにして見た。javascriptはまだ全然分からない。

index.hmtl

<!DOCTYPE html>
<html lang="ja" dir="ltr">
	<head>
		<title></title>
		<meta charset="UTF-8"/>
		<script src="./main.js"></script>
	</head>
	<body onload='main();'>
		<canvas id="canvas1" width="400" height="400">
		</canvas>
		<div>
			<p>キャンバス上でクリックでスタート/ストップ</p>
		</div>
	</body>
</html>

main.js

/**
 * 2012/12/05
 * Canvasサンプル
 *
 * */

var canvas, ctx;
var ball
var v
var isStopFlg;

Ball = function(x, y, r) {
        this.x = x;
        this.y = y;
        this.r = r;
}

Velocity = function(x, y) {
        this.x = x;
        this.y = y;
}

function update() {
        ball.x += v.x;
        if( ball.x - ball.r < 0 || ball.x + ball.r > canvas.width ) {
                /* 次回の速度ベクトルを設定 */
                v.x = -v.x;
      }

        ball.y += v.y;
        if( ball.y - ball.r < 0 || ball.y + ball.r > canvas.height ) {
                /* 次回の速度ベクトルを設定 */
                v.y = -v.y;
        }
}

function draw() {
        /* 背景の描画 */
        ctx.fillStyle="#000000";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        /* ボールの描画 */
        ctx.beginPath();
        ctx.fillStyle = 'rgb(192, 80, 77)'; // 赤
        ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI*2, false);
        ctx.fill();
}

function timerHandler() {
        if (!isStopFlg) {
                update()
                draw()
        }
        /* 次回のタイマーハンドラの登録 */
        setTimeout(timerHandler, 100);
}

function addEventListener() {
        canvas.addEventListener('click', clickHandler, false);
}

function clickHandler() {
        isStopFlg = !isStopFlg;
}

function main() {
        canvas = document.getElementById("canvas1");
        ctx = canvas.getContext("2d");

        ball = new Ball(100, 100, 25);
        v    = new Velocity(5, 5); 
        isStopFlg = false;
        draw()
        addEventListener()
        // 10ミリ秒でタイマーハンドラを呼び出す
        setTimeout(timerHandler, 10);
}