Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Maharramoff/064b6294bd79d06e16000ed9cf28080f to your computer and use it in GitHub Desktop.
Save Maharramoff/064b6294bd79d06e16000ed9cf28080f to your computer and use it in GitHub Desktop.
Canvas / Javascript game loop template
<!DOCTYPE html>
<html>
<head>
<title>Canvas / Javascript Game Template</title>
</head>
<body>
<style type="text/css">
html, body {
margin: 0;
padding: 0;
font-size: 10px;
}
body {
font-family: Calibri, 'Myriad Web Pro', sans-serif;
background-color: #333333;
color: #aaaaaa;
}
h1, h2, h3, h4, h5, h6 {
text-shadow: 0 -1px 0 #bbbbbb;
margin: 0;
font-size: 250%;
}
header {
margin: 3px 8px;
}
canvas {
display: block;
margin-left: auto;
margin-right: auto;
background-color: black;
}
</style>
<canvas id="main-canvas"></canvas>
<script type="text/javascript">
// Sample object to draw on screen
var Ball = function() {
this.position = {x: 0, y: 0};
this.size = 5;
this.speed = {x: 2, y: 1};
};
Ball.prototype.update = function() {
this.position.x += this.speed.x;
this.position.y += this.speed.y;
if (this.position.x > game.canvas.width || this.position.x < 0) {
this.speed.x *= -1;
}
if (this.position.y > game.canvas.height || this.position.y < 0) {
this.speed.y *= -1;
}
};
Ball.prototype.draw = function(ctx) {
ctx.fillStyle = '#333333';
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, this.size, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
};
var game = {
canvasId: 'main-canvas',
canvas: null,
ctx: null,
objects: [],
init: function() {
window.reqFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback){ window.setTimeout(callback, 1000 / 60); } })();
game.canvas = document.getElementById(game.canvasId);
game.ctx = game.canvas.getContext('2d');
game.setCanvasSizeToWindow();
game.objects.push(new Ball());
game.main();
},
setCanvasSizeToWindow: function() {
game.canvas.width = window.innerWidth;
game.canvas.height = window.innerHeight;
},
main: function() {
// The main loop called when a new animation frame is requested
game.update();
// game.clearCanvas();
game.draw();
reqFrame(game.main);
},
clearCanvas: function() {
game.ctx.clearRect(0, 0, game.canvas.width, game.canvas.height);
},
update: function() {
// Sample object updating code
for (var obj in game.objects) {
game.objects[obj].update();
}
},
draw: function() {
// Sample object drawing code
for (var obj in game.objects) {
game.objects[obj].draw(game.ctx);
}
}
};
game.init();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment