-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
75 lines (59 loc) · 1.63 KB
/
game.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback, element ){window.setTimeout(callback, 25);};
})();
var game = {
frames: 0,
fps: 25,
scene: null,
lastUpdate: 0,
display: null,
displayCtx: null,
buffer: null,
bufferCtx: null,
init: function() {
this.display = document.getElementById('gameframe');
this.displayCtx = this.display.getContext('2d');
this.buffer = document.createElement('canvas');
this.bufferCtx = this.buffer.getContext('2d');
this.buffer.width = this.display.width;
this.buffer.height = this.display.height;
var self = this;
setInterval( function() { self.updateFramerate(); }, 1000 );
this.lastUpdate = Date.now();
this.loop();
},
updateFramerate: function() {
this.fps = this.frames;
this.frames = 0;
},
loop: function() {
var now = Date.now();
var delta = now - this.lastUpdate;
if( delta < 250 && this.scene ) {
this.update( delta );
this.draw();
}
this.lastUpdate = now;
this.frames++;
var self = this;
requestAnimFrame( function() { self.loop(); });
},
update: function( delta ) {
this.scene.update( delta );
},
draw: function() {
this.buffer.width = this.buffer.width;
this.scene.draw( this.bufferCtx );
this.display.width = this.display.width;
this.displayCtx.drawImage( this.buffer, 0, 0 );
// fsps display
this.displayCtx.fillStyle = 'white';
this.displayCtx.font = '10px monospace';
this.displayCtx.fillText( this.fps, 600, 460 );
}
}