46 lines
1.1 KiB
TypeScript
Raw Normal View History

2024-03-01 18:56:58 -07:00
import { useState, useEffect, useRef } from "react";
import { TheAbstractionEngine, Game } from "../engine";
2024-03-02 06:00:47 -07:00
import { Miscellaneous } from "../engine/config";
2024-03-01 16:31:27 -07:00
export interface GameCanvasProps {
width: number;
height: number;
}
export const GameCanvas = ({ width, height }: GameCanvasProps) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
2024-03-02 01:07:55 -07:00
const [game, setGame] = useState<TheAbstractionEngine>();
2024-03-01 18:56:58 -07:00
useEffect(() => {
2024-03-02 01:07:55 -07:00
if (canvasRef.current && !game) {
2024-03-01 18:56:58 -07:00
const canvas = canvasRef.current;
const ctx = canvas.getContext("2d");
if (ctx) {
const game = new Game();
const theAbstractionEngine = new TheAbstractionEngine(game, ctx);
theAbstractionEngine.init().then(() => {
theAbstractionEngine.play();
setGame(theAbstractionEngine);
2024-03-02 06:00:47 -07:00
canvas.focus();
2024-03-01 18:56:58 -07:00
});
return () => theAbstractionEngine.stop();
}
}
}, [canvasRef]);
2024-03-01 16:31:27 -07:00
return (
<div className="centered-game">
2024-03-02 06:00:47 -07:00
<canvas
id={Miscellaneous.CANVAS_ID}
tabIndex={1}
ref={canvasRef}
width={width}
height={height}
></canvas>
2024-03-01 16:31:27 -07:00
</div>
);
};