JSFiddle - React, Tailwind, and code Playground
HTML
<div class='container'>
<canvas class='canvas'>
</canvas>
</div>
CSS
.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*/
JavaScript
'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)){
console.clear();
console.log(bounds);
console.log(rect.top);
console.log(`y ${y}`);
console.log(`(${bounds} * ${i}) - 1 = ${(bounds *...