Skip to content

Instantly share code, notes, and snippets.

@dfrankland
Last active April 12, 2017 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfrankland/22ed205eb6be2904acc127f9a2ecc41c to your computer and use it in GitHub Desktop.
Save dfrankland/22ed205eb6be2904acc127f9a2ecc41c to your computer and use it in GitHub Desktop.
HTML5 canvas game skeleton
(() => {
const RECT_SIZE = 5;
const RECT_SPEED = 5;
// Game state
const Store = class {
constructor(state = {}) {
this.state = state;
}
getState() {
return this.state;
}
setState(newState) {
if (this.state === newState) throw new Error('You must supply a new object when updating the state');
this.state = newState;
}
};
const store = new Store({ x: 0, y: 0 });
// Game event listener, this updates the game state
document.addEventListener('keydown', event => {
event.preventDefault();
const state = store.getState();
switch (event.code) {
case 'ArrowUp':
store.setState(Object.assign({}, state, { y: state.y - RECT_SIZE }));
break;
case 'ArrowDown':
store.setState(Object.assign({}, state, { y: state.y + RECT_SIZE }));
break;
case 'ArrowRight':
store.setState(Object.assign({}, state, { x: state.x + RECT_SIZE }));
break;
case 'ArrowLeft':
store.setState(Object.assign({}, state, { x: state.x - RECT_SIZE }));
break;
default:
break;
}
console.log('Current position: ', store.getState());
});
// Draw canvas, this gets the state and draws
const draw = (canvas, ctx) => {
const { x, y } = store.getState();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.rect(x, y, RECT_SIZE, RECT_SIZE);
ctx.closePath();
ctx.stroke();
};
// Game loop, tells the game when to draw
const mainGameLoop = (canvas, ctx) => () => {
draw(canvas, ctx);
requestAnimationFrame(mainGameLoop(canvas, ctx));
};
// Reset the body margin
document.body.style.margin = 0;
// Canvas responsive util
const setCanvasSize = canvas => (event, width = innerWidth, height = innerHeight) => {
canvas.width = width;
canvas.height = height;
};
// Create the canvas, start responsive utils, and get canvas context
const node = document.createElement('canvas');
const canvas = document.body.appendChild(node);
const resizeCanvas = setCanvasSize(canvas);
resizeCanvas();
window.onresize = resizeCanvas;
const ctx = canvas.getContext('2d');
// Start the game loop!
requestAnimationFrame(mainGameLoop(canvas, ctx));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment