Chromium 10.0.648.205 (81283) Ubuntu 10.10 にて動作確認した。
game.html
<html>
<head>
<script type="text/javascript" src="game.js"></script>
<title>game</title>
</head>
<body onload="init();">
<canvas id="c1" width="640" height="480">
canvas is not available
</canvas>
</body>
</html>
game.js
const FPS = 30;
var canvas1;
var context;
var drawIntervalVar;
var x = 0;
var y = 0;
const RECTSIZE = 20;
function init() {
canvas1 = document.getElementById('c1');
if(canvas1 == null) {
console.log("canvas is null");
return false;
}
context = canvas1.getContext('2d');
drawIntervalVar = setInterval(draw, 1000/FPS);
document.onkeydown = keyEvent;
}
function draw() {
context.clearRect(0,0,c1.width,c1.height);
context.fillRect(x,y,RECTSIZE,RECTSIZE);
}
function keyEvent(e) {
if(e.keyCode == 37) { //left
moveLeft();
} else if(e.keyCode == 38) { //up
moveUp();
} else if(e.keyCode == 39) { //right
moveRight();
} else if(e.keyCode == 40) { //down
moveDown();
}
}
function moveLeft() {
if(x > 0) {
x -= 10;
} else {
x = 0;
}
}
function moveRight() {
if(x < canvas1.width - RECTSIZE) {
x += 10;
} else {
x = canvas1.width - RECTSIZE;
}
}
function moveUp() {
if(y > 0) {
y -= 10;
} else {
y = 0;
}
}
function moveDown() {
if(y < canvas1.height - RECTSIZE) {
y += 10;
} else {
y = canvas1.height - RECTSIZE;
}
}