Here is a "hello world" simple skeleton I wrote to get started on an HTML5/javascript game. I converted it from a python example provided in Coursera's "An Introduction to Interactive Programming in Python" which demonstrates how to start moving a ball around a canvas using arrow keys.
I did this as a learning exercise to get to grips with javascript. While I've got this code to pass jslint, I was wondering if more experienced javascript coders could suggest better ways of doing this.
var canvas, context, ball_pos, vel, keys = {};
var BALL_RADIUS = 20;
function init() {
'use strict';
canvas = document.getElementById('c');
context = canvas.getContext('2d');
ball_pos = [canvas.width / 2, canvas.height / 2];
vel = 4;
}
function draw() {
'use strict';
// draw background
context.fillStyle = 'black';
context.fillRect(0, 0, canvas.width, canvas.height);
// draw ball
context.strokeStyle = 'red';
context.lineWidth = 2;
context.fillStyle = 'white';
context.beginPath();
context.arc(ball_pos[0], ball_pos[1], BALL_RADIUS, 0, Math.PI * 2, true);
context.closePath();
context.fill();
context.stroke();
}
function keydown(evt) {
'use strict';
// mozilla based browsers return which and others keyCode
var keyCode = evt.which || evt.keyCode;
keys[keyCode] = true;
// alert(keyCode)
// 33 up right
// 34 down right
// 35 down right
// 36 up left
if (keys[37]) { // left
ball_pos[0] -= vel;
}
if (keys[38]) { // up
ball_pos[1] -= vel;
}
if (keys[39]) { // right
ball_pos[0] += vel;
}
if (keys[40]) { // down
ball_pos[1] += vel;
}
}
function keyup(evt) {
'use strict';
var keyCode = evt.which || evt.keyCode;
delete keys[keyCode];
}
function animate() {
'use strict';
window.requestAnimationFrame(animate);
draw();
}
// register event handlers
window.onkeydown = keydown;
window.onkeyup = keyup;
init();
animate();
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<canvas id="c" width="600" height="400"></canvas>
</body>
</html>