From 1bb2d924ce7ed1016c1df94d451efaf48ee7132f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Mauduit?= Date: Wed, 10 Jun 2020 21:02:48 +0200 Subject: [PATCH] Fix Canvas cell position compute from tutorial --- www/index.js | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/www/index.js b/www/index.js index 86259e0..2ba463a 100644 --- a/www/index.js +++ b/www/index.js @@ -6,12 +6,12 @@ import { Universe, Cell } from "wasm-game-of-life"; let req_id; let stop = false; -const CELL_SIZE = 40; // px +const CELL_SIZE = 9; // px const GRID_COLOR = "#CCCCCC"; const DEAD_COLOR = "#FFFFFF"; const ALIVE_COLOR = "#3399FF"; -const universe = Universe.new(10,10); +const universe = Universe.new(128,128); const width = universe.width(); const height = universe.height(); @@ -36,18 +36,16 @@ const renderLoop = async () => { function getCursorPos(canvas, evt) { const rect = canvas.getBoundingClientRect(); - // Bound check: It seems that the last case can overlap - let x = Math.trunc((evt.clientX - rect.left) / CELL_SIZE); - if (x >= (width)) - x = x - 1; + const scaleX = canvas.width / rect.width; + const scaleY = canvas.height / rect.height; - let y = Math.trunc((evt.clientY - rect.top) / CELL_SIZE); - if (y >= (height)) - y = y - 1; + const canvasLeft = (evt.clientX - rect.left) * scaleX; + const canvasTop = (evt.clientY - rect.top) * scaleY; - return { x, - y, - }; + const row = Math.min(Math.floor(canvasTop / (CELL_SIZE + 1)), height - 1); + const col = Math.min(Math.floor(canvasLeft / (CELL_SIZE + 1)), width - 1); + + return { row, col }; } canvas.addEventListener('mouseover', @@ -69,14 +67,14 @@ canvas.addEventListener('click', var mousePos = getCursorPos(canvas, evt); let cellsPtr = universe.cells(); let cells = new Uint8Array(memory.buffer, cellsPtr, width * height); - console.log("Click position : X = " + (mousePos.x) + ", Y = " + (mousePos.y)); - const idx = universe.get_index(mousePos.y, mousePos.x); + console.log("Click position : X = " + (mousePos.row) + ", Y = " + (mousePos.col)); + const idx = universe.get_index(mousePos.row, mousePos.col); if (cells[idx] === Cell.Dead) console.log("Cell[" + idx + "] is : " + "Dead !"); else console.log("Cell[" + idx + "] is : " + "Alive !"); - // Change to inverse ! + // Toggle it ! TODO: Do it (like in the tutorial) from Rust ! cells[idx] = (cells[idx] === Cell.Dead) ? Cell.Alive : Cell.Dead; drawCells(); });