Canvas game
HTML
<canvas id="canvas" width="300" height="300"></canvas>
<p>To control, click Result part of JS Fiddle and use arrows</p>
CSS
canvas {
border: 1px red solid;
}
JavaScript
var move = 0; // 0 - stop, 1 - move
// Direction:
// 0 - left
// 1 - top
// 2 - right
// 3 - down
// 4 - stop
var direction = 4;
var lastX = 10;
var lastY = 10;
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.clearRect(0,0,300,300); // Clear canvas
// for (var x = 0.5; x < 300; x += 10) {ctx.moveTo(x, 0);ctx.lineTo(x, 300);}for (var y = 0.5; y < 300; y += 10) {ctx.moveTo(0, y);ctx.lineTo(300, y);}ctx.strokeStyle = "#ddd";ctx.stroke(); // Grid
switch (direction) {
case 0:
lastX -= 1;
if (lastX < 0) lost(ctx);
break;
case 1:
lastY -= 1;
if (lastY < 0) lost(ctx);
break;
case 2:
lastX += 1;
if(lastX > 200) lost(ctx);
break;
case 3:
lastY += 1;
if (lastY > 200) lost(ctx);
break;
default:
// no movement
break;
}
ctx.fillRect(lastX, lastY, 100, 100);
if (move == 1) {
window.requestAnimationFrame(draw);
}
}
document.addEventListener('DOMContentLoaded', draw, false);
// document.getElementById('control').onkeydown = test;
window.onkeydown = test;
function test(e) {
switch (e.keyCode) {
case 37:
console.log('Left');
direction = 0;
break;
case 38:
console.log('Top');
direction = 1;
break;
case 39:
console.log('Right');
direction = 2;
break;
case 40:
console.log('Down');
direction = 3;
break;
case 32:
console.log('Space');
if (move == 1) move = 0;
else if (move == 0) {
move = 1;
draw();
}
console.log(move);
break;
default:
console.log('Other');
break;
...