import Config from "./GameConfig.js"; import Time from "../utils/Time.js"; var canvas, context, gameVersion, fpsBuffer, currentFPS; function draw(state) { updateFPS(state.delta); context.clearRect(0, 0, canvas.width, canvas.height); drawEnemies(state.enemies); drawGazePoints(state.gazePoints); if (state.debug === true) { drawDebugInfo(); } } // 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(); } } function drawEnemies(enemies) { context.fillStyle = Config.DEFAULT_ENEMEY_COLOR; for (let i = 0; i < enemies.length; i++) { drawSingleEnemey(enemies[i]); } } 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(); } function drawGazePoints(gazePoints) { context.fillStyle = Config.DEFAULT_GAZE_POINT_COLOR; for (let i = 0; i < gazePoints.length; i++) { drawSingleGazePoint(gazePoints[i]); } } 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(); } function drawDebugInfo() { context.beginPath(); 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); context.closePath(); } class GameRenderer { init(gameCanvas, width, height, version) { fpsBuffer = []; currentFPS = 0; gameVersion = version; canvas = gameCanvas; canvas.width = width; canvas.height = height; canvas.style.width = `${width}px`; canvas.style.height = `${height}px`; context = canvas.getContext("2d", { alpha: false }); canvas.style.backgroundColor = Config.BACKGROUND_COLOR; } render(state) { draw(state); } } export default new GameRenderer();