The x and y position of the grid on the canvas is being put 1 row to the left and 1 column above on some cells. I don't know what's causing this but it mostly happens in the middle to nearing the end of the grid.
'use strict';
// the canvas
const canvas = document.querySelector('.canvas');
const context = canvas.getContext('2d');
class Node {
constructor(row, col) {
// save current index (row, col) to know where in the canvas it is
this.row = row;
this.col = col;
this.show = color => {
context.beginPath();
context.rect(this.row * cellDimension, this.col * cellDimension, cellDimension - 1, cellDimension - 1);
context.fillStyle = color;
context.fill();
}
}
}
// the counter from input field
const colRowCount = 60;
// will be determined from setup
let cellDimension;
let gridArray = new Array(colRowCount);
//start and finish
let startNode = new Node();
let endNode = new Node();
// array of the path nodes
let totalPath = new Array();
// setup all the neccessities
const setup = () => {
// subtract the height of menu
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
cellDimension = canvas.width / colRowCount;
for (let i = 0; i < colRowCount; i++) {
gridArray[i] = new Array(colRowCount);
for (let j = 0; j < colRowCount; j++) {
gridArray[i][j] = new Node(i, j);
}
}
context.beginPath();
for (let i = 0; i < canvas.width; i += cellDimension) {
// horizontal divider
context.moveTo(0, i);
context.lineTo(canvas.width, i);
// vertical divider
context.moveTo(i, 0);
context.lineTo(i, canvas.width);
context.strokeStyle = '#ddd';
context.stroke();
}
}
const getMousePosition = event => {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
// top left
let cellX = 0;
let cellY = 0;
// bounds of the square unit
const bounds = Math.floor(Math.floor(canvas.width) / colRowCount);
for (let i = 1; i < colRowCount; i++) {
if (x > (bounds * i)) {
cellX = i;
}
if (y > (bounds * i)) {
cellY = i;
}
}
return {
x: cellX,
y: cellY
};
}
const placeStart = position => {
startNode = gridArray[position.x][position.y];
startNode.show('green');
}
window.addEventListener('load', () => {
// setup the canvas
setup();
// event listener for canvas
canvas.addEventListener('mousedown', event => {
placeStart(getMousePosition(event));
});
});
.container {
height: calc(100% - 50px);
width: 100%;
}
/*for all the grids with canvas*/
.canvas {
height: 100%;
width: 100%;
border: 1px solid green;
}
/*for all the grids with canvas*/
<div class='container'>
<canvas class='canvas'>
</canvas>
</div>
The one in the jsfiddle is behaving much more unexpectedly.