-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
fps-meter.js
119 lines (99 loc) · 2.6 KB
/
fps-meter.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import { Blaze } from 'meteor/blaze';
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (() => {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
}
const getTime = () => {
return (window.performance && window.performance.now) ? window.performance.now() : +new Date();
};
class FPSMeter {
constructor(opts) {
this.ui = opts.ui || false;
this.reactive = opts.reactive || false;
if (this.reactive === true) {
this.fps = new ReactiveVar(0);
} else {
this.fps = 0;
}
this.isRunning = false;
this.template = null;
}
measure() {
const time = getTime();
window.requestAnimationFrame(() => {
const _fps = Math.round((1 / (getTime() - time)) * 1000);
if (this.reactive === true) {
this.fps.set(_fps);
} else {
this.fps = _fps;
}
if (this.ui && this.element) {
let i = 4 - `${_fps}`.length;
let pad = '';
while (i > 0) {
pad += ' ';
i--;
}
this.text.nodeValue = `${_fps}${pad}fps`;
switch (false) {
case !(_fps < 7):
this.element.className = 'dead';
break;
case !(_fps < 25):
this.element.className = 'danger';
break;
case !(_fps < 40):
this.element.className = 'warn';
break;
case !(_fps > 70):
this.element.className = 'high';
break;
default:
this.element.className = '';
break;
}
}
if (this.isRunning) {
this.measure();
}
});
}
start() {
if (!this.isRunning) {
this.isRunning = true;
if (this.ui === true && Blaze) {
this.template = Blaze.render(Template.FPSMeter, document.body);
this.text = document.createTextNode('');
this.element = this.template.templateInstance().find('#__FPSMeter');
this.element.appendChild(this.text);
}
this.measure();
}
}
pause() {
this.isRunning = false;
}
resume() {
if (!this.isRunning) {
this.isRunning = true;
this.measure();
}
}
toggle() {
this.isRunning ? this.pause() : this.resume();
}
stop() {
if (this.isRunning) {
this.isRunning = false;
if (this.ui === true && Blaze && this.template) {
Blaze.remove(this.template);
}
}
}
}
export { FPSMeter };