Snake in HTML5 Canvas
HTML
<html>
<head>
<script type="text/javascript" language="javascript">
// Box width
var bw = 400;
// Box height
var bh = 400;
// Padding
var p = 10;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
function drawBoard(){
for (var x = 0; x <= bw; x += 40) {
context.moveTo(0.5 + x + p, p);
context.lineTo(0.5 + x + p, bh + p);
}
for (var x = 0; x <= bh; x += 40) {
context.moveTo(p, 0.5 + x + p);
context.lineTo(bw + p, 0.5 + x + p);
}
context.strokeStyle = "black";
context.stroke();
}
drawBoard();
</script>
</head>
<body style=" background: lightblue;">
<canvas id="canvas" width="420px" height="420px" style="background: #fff; margin:20px"></canvas>
</body>
</html>
CSS
article, aside, details, figcaption, figure, footer, header,
hgroup, menu, nav, section {
display: block;
}
body {
background-color: #CCC;
}
h1 {
text-align: center;
}
p {
text-align: center;
}
canvas {
display: block;
margin: 0 auto;
background-color: #666;
}
JavaScript
var canvas = document.getElementById("the-game");
var context = canvas.getContext("2d");
game = {
score: 0,
fps: 8,
over: false,
message: null,
start: function() {
game.over = false;
game.message = null;
game.score = 0;
game.fps = 8;
snake.init();
food.set();
},
stop: function() {
game.over = true;
game.message = 'GAME OVER - PRESS SPACEBAR';
},
drawBox: function(x, y, size, color) {
context.fillStyle = color;
context.beginPath();
context.moveTo(x - (size / 2), y - (size / 2));
context.lineTo(x + (size / 2), y - (size / 2));
context.lineTo(x + (size / 2), y + (size / 2));
context.lineTo(x - (size / 2), y + (size / 2));
context.closePath();
context.fill();
},
drawScore: function() {
context.fillStyle = '#999';
context.font = (canvas.height) + 'px Impact, sans-serif';
context.textAlign = 'center';
context.fillText(game.score, canvas.width/2, canvas.height * .9);
},
drawMessage: function() {
if (game.message !== null) {
context.fillStyle = '#00F';
context.strokeStyle = '#FFF';
context.font = (canvas.height / 10) + 'px Impact';
context.textAlign = 'center';
context.fillText(game.message, canvas.width/2, canvas.height/2);
context.strokeText(game.message, canvas.width/2, canvas.height/2);
}
},
resetCanvas: function() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
};
snake = {
size: canvas.width / 40,
x: null,
y: null,
color: '#0F0',
direction: 'left',
sections: [],
init: function() {
snake.sections = [];
snake.direction = 'left';
snake.x = canvas.width / 2 + snake.size / 2;
snake.y = canvas.height /2 + snake.size / 2;
for (i = snake.x + (5 * snake.size); i >= snake.x; i-=snake.size) {
snake.sections.push(i + ',' + snake.y);
}
},
move: function() {
switch(snake.direction) {
case 'up':
...