GameRenderer.js 2.14 KB
Newer Older
1 2
import Config from "./GameConfig.js";
import Time from "../utils/Time.js";
3

4
var canvas,
5
  context,
6 7 8
  gameVersion,
  fpsBuffer,
  currentFPS;
9

10 11
function draw(state) {
  updateFPS(state.delta);
12
  context.clearRect(0, 0, canvas.width, canvas.height);
13
  drawObjects(state.objects);
14 15
  drawGazePoints(state.gazePoints);
  if (state.debug === true) {
16 17 18 19
    drawDebugInfo();
  }
}

20 21 22 23 24 25 26 27 28
// Move fps callculation to manager since we need it there to use delta
function updateFPS(delta) {
  let fps = Time.ONE_SECOND_IN_MS / delta;
  fpsBuffer.push(fps);
  if (fpsBuffer.length === Config.FPS_BUFFER_LENGTH) {
    currentFPS = parseInt(fpsBuffer.reduce((a, b) => a + b, 0) /
      fpsBuffer.length);
    fpsBuffer.shift();
  }
29 30
}

31 32 33
function drawObjects(objects) {
  for (let i = 0; i < objects.length; i++) {
    objects[i].draw(context);
34
  }
35 36
}

37 38 39 40
function drawGazePoints(gazePoints) {
  context.fillStyle = Config.DEFAULT_GAZE_POINT_COLOR;
  for (let i = 0; i < gazePoints.length; i++) {
    drawSingleGazePoint(gazePoints[i]);
41 42 43
  }
}

44
function drawSingleGazePoint(gazePoint) {
45 46
  let inversedAge = 1 - gazePoint.relativeAge,
    radius = inversedAge * Config.DEFAULT_GAZE_POINT_RADIUS;
47
  context.save();
48
  context.globalAlpha = inversedAge;
49 50 51 52 53 54
  context.beginPath();
  context.ellipse(gazePoint.targetX, gazePoint.targetY, radius, radius, Math.PI /
    4, 0, 2 * Math.PI);
  context.closePath();
  context.fill();
  context.restore();
55 56 57 58
}

function drawDebugInfo() {
  context.beginPath();
59 60 61 62
  context.font = Config.DEBUG_FONT;
  context.fillStyle = Config.DEBUG_COLOR;
  context.fillText(`${gameVersion} | ${currentFPS}fps`, Config.DEBUG_POSITION_OFFSET,
    canvas.height - Config.DEBUG_POSITION_OFFSET);
63 64 65 66 67
  context.closePath();
}

class GameRenderer {

68
  init(gameCanvas, width, height, version) {
69
    fpsBuffer = [];
70 71 72 73 74 75 76
    currentFPS = 0;
    gameVersion = version;
    canvas = gameCanvas;
    canvas.width = width;
    canvas.height = height;
    canvas.style.width = `${width}px`;
    canvas.style.height = `${height}px`;
77
    context = canvas.getContext("2d", { alpha: false });
78
    canvas.style.backgroundColor = Config.BACKGROUND_COLOR;
79 80
  }

81 82
  render(state) {
    draw(state);
83 84 85 86 87
  }

}

export default new GameRenderer();