JSFiddle - React, Tailwind, and code Playground
by Josh Pullen
HTML
<canvas id="canvas"></canvas>
CSS
html, body {
margin:0px;
padding:0px;
overflow:hidden;
}
JavaScript
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
gridSize = 50; // Space between lines in px
lengthDivision = 5; // Bigger is shorter, smaller is longer (because science)
function drawAll(mx, my) {
// Sets canvas size to full page and (helpfully) clears the canvas
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
for (y = 1; y < window.innerHeight / gridSize; y++) {
for (x = 1; x < window.innerWidth / gridSize; x++) {
ctx.moveTo(x * gridSize, y * gridSize);
ctx.lineTo(x * gridSize + (x * gridSize - mx) / lengthDivision, y * gridSize + (y * gridSize - my) / lengthDivision);
ctx.stroke();
}
}
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
canvas.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(canvas, evt);
drawAll(mousePos.x, mousePos.y);
}, false);