GameRenderer.js 2.54 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 14 15
  drawEnemies(state.enemies);
  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 34 35
function drawEnemies(enemies) {
  context.fillStyle = Config.DEFAULT_ENEMEY_COLOR;
  for (let i = 0; i < enemies.length; i++) {
    drawSingleEnemey(enemies[i]);
  }
36 37
}

38 39 40 41 42 43 44 45 46 47 48
function drawSingleEnemey(enemy) {
  context.save();
  context.beginPath();
  context.translate(enemy.x, enemy.y + enemy.height/2);
  context.rotate(enemy.direction);
  context.moveTo(0,-enemy.height/2);
  context.lineTo(-(enemy.width/2), enemy.height/2);
  context.lineTo(enemy.width/2, enemy.height/2);
  context.closePath();
  context.fill();
  context.restore();
49 50
}

51 52 53 54
function drawGazePoints(gazePoints) {
  context.fillStyle = Config.DEFAULT_GAZE_POINT_COLOR;
  for (let i = 0; i < gazePoints.length; i++) {
    drawSingleGazePoint(gazePoints[i]);
55 56 57
  }
}

58 59 60 61 62 63 64 65 66 67
function drawSingleGazePoint(gazePoint) {
  let radius = gazePoint.inversedAge * Config.DEFAULT_GAZE_POINT_RADIUS;
  context.save();
  context.globalAlpha = gazePoint.inversedAge;
  context.beginPath();
  context.ellipse(gazePoint.targetX, gazePoint.targetY, radius, radius, Math.PI /
    4, 0, 2 * Math.PI);
  context.closePath();
  context.fill();
  context.restore();
68 69 70 71
}

function drawDebugInfo() {
  context.beginPath();
72 73 74 75
  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);
76 77 78 79 80
  context.closePath();
}

class GameRenderer {

81
  init(gameCanvas, width, height, version) {
82
    fpsBuffer = [];
83 84 85 86 87 88 89
    currentFPS = 0;
    gameVersion = version;
    canvas = gameCanvas;
    canvas.width = width;
    canvas.height = height;
    canvas.style.width = `${width}px`;
    canvas.style.height = `${height}px`;
90
    context = canvas.getContext("2d", { alpha: false });
91
    canvas.style.backgroundColor = Config.BACKGROUND_COLOR;
92 93
  }

94 95
  render(state) {
    draw(state);
96 97 98 99 100
  }

}

export default new GameRenderer();