77 lines
2.3 KiB
JavaScript
77 lines
2.3 KiB
JavaScript
// file: Tauri/game-reflex-poc/frontend/main.js
|
|
// version: 1
|
|
|
|
import init, { ReflexWasmGame } from "./game_reflex_poc_tauri.js";
|
|
|
|
const FRAME_MS = 16;
|
|
|
|
function color(red, green, blue) {
|
|
return `rgb(${red} ${green} ${blue})`;
|
|
}
|
|
|
|
function resizeCanvas(canvas) {
|
|
const ratio = window.devicePixelRatio || 1;
|
|
const width = Math.max(1, Math.floor(canvas.clientWidth * ratio));
|
|
const height = Math.max(1, Math.floor(canvas.clientHeight * ratio));
|
|
if (canvas.width !== width || canvas.height !== height) {
|
|
canvas.width = width;
|
|
canvas.height = height;
|
|
}
|
|
}
|
|
|
|
function render(game, canvas, context, score) {
|
|
resizeCanvas(canvas);
|
|
context.fillStyle = color(game.background_red(), game.background_green(), game.background_blue());
|
|
context.fillRect(0, 0, canvas.width, canvas.height);
|
|
|
|
const count = game.rectangle_count();
|
|
for (let index = 0; index < count; index += 1) {
|
|
context.fillStyle = color(game.rectangle_red(index), game.rectangle_green(index), game.rectangle_blue(index));
|
|
context.fillRect(
|
|
game.rectangle_x(index) * canvas.width,
|
|
game.rectangle_y(index) * canvas.height,
|
|
game.rectangle_width(index) * canvas.width,
|
|
game.rectangle_height(index) * canvas.height,
|
|
);
|
|
}
|
|
|
|
score.value = `Score : ${game.score()}`;
|
|
}
|
|
|
|
async function start() {
|
|
await init();
|
|
|
|
const canvas = document.querySelector("#game");
|
|
const score = document.querySelector("#score");
|
|
const context = canvas.getContext("2d");
|
|
if (!(canvas instanceof HTMLCanvasElement) || !(score instanceof HTMLOutputElement) || context === null) {
|
|
throw new Error("Reflex Tauri frontend DOM is incomplete");
|
|
}
|
|
|
|
const game = new ReflexWasmGame();
|
|
canvas.addEventListener("pointerdown", (event) => {
|
|
const bounds = canvas.getBoundingClientRect();
|
|
const x = (event.clientX - bounds.left) / bounds.width;
|
|
const y = (event.clientY - bounds.top) / bounds.height;
|
|
game.pointer_down(x, y);
|
|
render(game, canvas, context, score);
|
|
});
|
|
|
|
let previous = performance.now();
|
|
function frame(now) {
|
|
while (now - previous >= FRAME_MS) {
|
|
game.tick();
|
|
previous += FRAME_MS;
|
|
}
|
|
render(game, canvas, context, score);
|
|
window.requestAnimationFrame(frame);
|
|
}
|
|
|
|
render(game, canvas, context, score);
|
|
window.requestAnimationFrame(frame);
|
|
}
|
|
|
|
start().catch((error) => {
|
|
console.error("Reflex Tauri WASM startup failed", error);
|
|
});
|