Source: Frontend/game/fps-counter.js

  1. /* global PIXI */
  2. /** @module FpsCounter */
  3. let ml = window.ml || (window.ml = {});
  4. ml.FPS_BUFFER_SIZE = 25;
  5. /**
  6. * A basic fps counter
  7. */
  8. export default class FpsCounter {
  9. constructor() {
  10. this._avgBuf = [];
  11. this._lastFrame = 0;
  12. this._textStyle = new PIXI.TextStyle({
  13. fill: "#fff",
  14. fontSize: 17
  15. });
  16. this.sprite = new PIXI.Text("Loading", this._textStyle);
  17. }
  18. /**
  19. * Update and render the fps counter (should be called every frame)
  20. */
  21. update() {
  22. let now = Date.now();
  23. if(this._lastFrame > 0) {
  24. this._avgBuf.push(now - this._lastFrame);
  25. }
  26. this._lastFrame = now;
  27. while(this._avgBuf.length > ml.FPS_BUFFER_SIZE) {
  28. this._avgBuf.shift();
  29. }
  30. /* eslint-disable arrow-body-style */
  31. let frameTime = Math.round(this._avgBuf.reduce((a, b) => a + b, 0) / this._avgBuf.length);
  32. /* eslint-enable arrow-body-style */
  33. let text = `${frameTime}ms (${Math.round(1000 / frameTime)}fps)`;
  34. this.sprite.setText(text);
  35. let metrics = PIXI.TextMetrics.measureText(text, this._textStyle);
  36. this.sprite.position.set(innerWidth - 10 - metrics.width, 10);
  37. }
  38. }