JSFiddle - React, Tailwind, and code Playground

by Rajesh Danabal

HTML

<canvas id="quadtreeCanvas" width="800" height="600"></canvas>
    <script src="quadtree.js"></script>

JavaScript

// quadtree.js

// Set canvas dimensions
const canvas = document.getElementById('quadtreeCanvas');
const context = canvas.getContext('2d');

// Create random points to populate the quadtree
const points = d3.range(100).map(() => ({
    x: Math.random() * canvas.width,
    y: Math.random() * canvas.height
}));

// Create a D3 quadtree
const quadtree = d3.quadtree()
    .x(d => d.x)
    .y(d => d.y)
    .addAll(points);

// Function to draw the quadtree
function drawQuadtree(node) {
    if (!node) return;
console.log(node)
    // Draw the bounding box for the current node
    context.strokeStyle = 'rgba(0, 255, 0, 0.5)'; // Green with some transparency
    context.lineWidth = 1;

    const x0 = node.x0, y0 = node.y0, x1 = node.x1, y1 = node.y1;
    context.strokeRect(x0, y0, x1 - x0, y1 - y0);

    // Recursively draw the children
    if (node.length) {
        drawQuadtree(node[0]); // Top-left
        drawQuadtree(node[1]); // Top-right
        drawQuadtree(node[2]); // Bottom-left
        drawQuadtree(node[3]); // Bottom-right
    }
}

// Clear canvas and draw the quadtree
context.clearRect(0, 0, canvas.width, canvas.height);
drawQuadtree(quadtree);

// Draw points on the canvas
context.fillStyle = 'red';
points.forEach(point => {
    context.beginPath();
    context.arc(point.x, point.y, 5, 0, 2 * Math.PI);
    context.fill();
});