Skip to content

Commit

Permalink
Allow user to paint cells by clicking and dragging
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisnewtn committed Jan 13, 2025
1 parent ceb6c1e commit c1f3b7a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
28 changes: 26 additions & 2 deletions public/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,12 @@ playPauseButton.addEventListener('click', () => {

play();

canvas.addEventListener('click', e => {
const toggled = new Set();

/**
* @param e {MouseEvent}
*/
const toggleCell = e => {
const boundingRect = canvas.getBoundingClientRect();

const scaleX = canvas.width / boundingRect.width;
Expand All @@ -143,8 +148,27 @@ canvas.addEventListener('click', e => {
const row = Math.min(Math.floor(canvasTop / (cellSize + CELL_BORDER)), height - CELL_BORDER);
const col = Math.min(Math.floor(canvasLeft / (cellSize + CELL_BORDER)), width - CELL_BORDER);

universe.toggle_cell(row, col);
const cell = `${row}:${col}`;

// prevents the user for erasing their cells as they draw them.
if (toggled.has(cell)) {
return;
}

toggled.add(cell);

universe.toggle_cell(row, col);
//drawGrid();
drawCells();
};

canvas.addEventListener('mousemove', e => {
if (e.buttons !== 1) {
return;
}
toggleCell(e);
});

canvas.addEventListener('mousedown', toggleCell);

canvas.addEventListener('mouseup', () => toggled.clear());
3 changes: 3 additions & 0 deletions public/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ body {
gap: 1rem;
align-content: stretch;
}
canvas {
cursor: crosshair;
}
.buttons {
display: flex;
flex-direction: row;
Expand Down

0 comments on commit c1f3b7a

Please sign in to comment.