Spatial Grid
by dirtyd77
HTML
<script src="https://rawgit.com/jrhdoty/generic-quadtree/master/quadtree.js"></script>
<canvas id="canvas" />
CSS
#canvas{
border: 1px solid;
}
Babel + JSX
const canvasHeight = 400;
const canvasWidth = 400;
const cellWidth = canvasWidth / 10;
const cellHeight = canvasHeight / 10;
const treeMin = new Point(0,0);
const treeMax = new Point(canvasWidth, canvasHeight);
const treeTotalArea = new Box(treeMin, treeMax);
const gridTree = new Quadtree(treeTotalArea);
let mouse = {
x: NaN,
y: NaN
};
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);
createTree();
doCanvasStuff();
function mouseMove ({offsetX, offsetY}) {
mouse.x = offsetX;
mouse.y = offsetY;
}
function doCanvasStuff () {
requestAnimationFrame(doCanvasStuff);
clear();
drawGrid();
draw();
}
function createTree() {
let counter = 0;
for (let i = 0; i < canvasWidth; i += cellWidth) {
let columnAlphaChar = String.fromCharCode(97 + counter);
let x = i;
for (let j = 0; j < canvasHeight; j += cellHeight) {
let y = j;
let pt = new Point(x, y);
console.log(gridTree);
gridTree.insert(pt, columnAlphaChar + j);
}
counter++;
}
}
function clear () {
context.fillStyle = 'white';
context.fillRect(0, 0, canvasWidth, canvasHeight);
}
function drawGrid () {
context.strokeStyle = 'black';
context.beginPath();
for (let i = 0; i < canvasWidth; i += cellWidth) {
for (let j = 0; j < canvasHeight; j += cellHeight) {
drawGridLines(i, j);
}
}
context.stroke();
}
function drawGridLines (x, y) {
context.moveTo(0, y);
context.lineTo(canvasWidth, y);
context.moveTo(x, 0);
context.lineTo(x, canvasHeight);
}
function drawMouseCircle () {
let radius = 10;
let xMin = mouse.x - radius;
let xMax = mouse.x + radius;
let yMin = mouse.y - radius;
let yMax = mouse.y + radius;
let minPt = new Point(xMin, yMin);
let maxPt = new Point(xMin, yMax);
let range = new Box(minPt, maxPt);
let result = gridTree.queryRange(range);
...