JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas" width="1050" height="1050"></canvas>
JavaScript
var canvas = document.getElementById('canvas');
var first = {}; var stop = false;
var ctx = canvas.getContext('2d');
if (canvas.getContext){
canvas.addEventListener('mousemove', function(e) {
var pos = getMousePos(canvas, e), /// provide this canvas and event
x = pos.x,
y = pos.y;
/// check x and y against the grid
}, false);
canvas.addEventListener('click', function(e) {
var pos = getMousePos(canvas, e), /// provide this canvas and event
x = pos.x,
y = pos.y;
if (Object.keys(first).length === 0) {
first.x = x;
first.y = y;
} else {
stop = true;
}
/// check x and y against the grid
}, false);
}
function getMousePos(canvas, e) {
var rect = canvas.getBoundingClientRect();
if (Object.keys(first).length !== 0 && !stop) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.strokeRect(first.x, first.y, e.clientX - rect.left,e.clientY - rect.top);
}
console.log( {x: e.clientX - rect.left, y: e.clientY - rect.top})
return {x: e.clientX - rect.left, y: e.clientY - rect.top};
}