Spatial Grid
by dirtyd77
HTML
<canvas id="canvas" />
CSS
#canvas{
border: 1px solid;
}
Babel + JSX
const canvasHeight = 400;
const canvasWidth = 400;
const gridCellSize = canvasHeight / 10;
const canvas = document.getElementById('canvas');
canvas.height = 400;
canvas.width = 400;
canvas.onmousemove = mouseMove;
const context = canvas.getContext('2d');
context.translate(0.5, 0.5);
let mouse = {
x: NaN,
y: NaN
};
doCanvasStuff();
function mouseMove ({offsetX, offsetY}) {
mouse.x = offsetX;
mouse.y = offsetY;
}
function doCanvasStuff () {
requestAnimationFrame(doCanvasStuff);
clear();
drawGrid();
draw();
}
function clear () {
context.fillStyle = 'rgb(255,255,255)';
context.fillRect(0, 0, canvasWidth, canvasHeight);
}
function drawGrid () {
context.strokeStyle = 'black';
context.beginPath();
for (let i = gridCellSize; i < canvasHeight; i += gridCellSize) {
context.moveTo(0, i);
context.lineTo(canvasWidth, i);
context.moveTo(i, 0);
context.lineTo(i, canvasHeight);
}
context.stroke();
}
function draw () {
context.strokeStyle = 'red';
context.lineWidth = 1;
context.beginPath();
context.moveTo(0, 0);
context.lineTo(mouse.x, mouse.y);
context.closePath();
context.stroke();
}