-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRenderer.js
59 lines (51 loc) · 1.38 KB
/
Renderer.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
window.requestAnimationFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function(f) {
window.setTimeout(f, 1e3 / 60);
};
// Universal class for rendering/updating at given FPS
export default class Renderer {
constructor(updateFun, fps = 30) {
this.fps = fps;
this.now = null;
this.then = Date.now();
this.interval = 1000 / fps;
this.delta = null;
// function which will be called to update the state
this.updateFun = updateFun;
// Renderer state variables
this.paused = false;
this.stopped = false;
}
redraw() {
if (this.stopped === true) return; // stop updating
// Browser will try to call this at 60fps
requestAnimationFrame(this.redraw.bind(this));
this.now = Date.now();
this.delta = this.now - this.then;
// We need to update the state only at FPS intervals (not 60fps)
// So skip unnecessary updates
if (this.delta > this.interval && this.paused === false) {
// interval difference
this.then = this.now - (this.delta % this.interval);
this.updateFun();
}
}
pause() {
this.paused = true;
}
unpause() {
this.paused = false;
}
stop() {
this.stopped = true;
}
start() {
this.stopped = false;
this.redraw();
}
}