Fix Canvas cell position compute from tutorial
parent
49ec2a21a5
commit
1bb2d924ce
28
www/index.js
28
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();
|
||||
});
|
||||
|
|
Loading…
Reference in New Issue