Как можно реализовать перемешенные по сетке? Что бы квадрат перемещался строго по сетке и не смог остановиться посередине клеточки
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");
const gridSettings = {
squareWidth: 30,
squareHeight: 30,
}
function renderGrid() {
ctx.beginPath()
const w = canvas.width
const h = canvas.height
const squareWidth = w / gridSettings.squareWidth
const squareHeight = h / gridSettings.squareHeight
ctx.strokeStyle = '#bdbdbd'
ctx.lineWidth = 0.4
for (let x = squareWidth; x < w; x += squareWidth) ctx.strokeRect(x, 0, 0.1, h)
for (let y = squareHeight; y < h; y += squareHeight) ctx.strokeRect(0, y, w, 0.1)
ctx.fill()
ctx.closePath()
}
const drawRect = (offsetX = 0, offsetY = 0) => {
ctx.fillStyle = "black";
ctx.clearRect(0, 0, 500, 600)
ctx.fillRect(offsetX, offsetY, 34, 40)
renderGrid()
}
drawRect(0, 0)
const rectPos = { x: 0, y: 0 }
const edge = (c, min, max) => Math.max(min, Math.min(max, c));
canvas.onmousedown = (e) => {
const start = { x: e.offsetX, y: e.offsetY };
canvas.onmousemove = (e) => {
drawRect(
edge(rectPos.x + e.offsetX - start.x, 0, 600 - 25),
edge(rectPos.y + e.offsetY - start.y, 0, 500 - 25)
);
}
canvas.onmouseup = (e) => {
rectPos.x = edge(rectPos.x + e.offsetX - start.x, 0, 600 - 25);
rectPos.y = edge(rectPos.y + e.offsetY - start.y, 0, 500 - 25);
canvas.onmousemove = null
}
}
<canvas id="canvas" style="border: 1px solid black;" width=500 height=600></canvas>
let diff = e.offsetX - start.x; let x = rectPos.x + Math.floor(diff / width) * width;