JSFiddle - React, Tailwind, and code Playground

by Rajesh Danabal

HTML

<canvas id="canvas"></canvas>

TypeScript

interface EventHandlers {
    [key: string]: ((e: MouseEvent) => void)[];
}


interface Boundary {
    x: number;
    y: number;
    width: number;
    height: number;
    contains?(shape: Shape): boolean; // Check if a shape is within the boundary
}

type TShape =
    | 'circle'
    | 'square'
    | 'cross'
    | 'diamond'
    | 'triangle-up'
    | 'triangle-down'
    | 'triangle-right'
    | 'triangle-left'
    | 'hexagon'
    | 'hexagon-rotated'
    | 'pentagon'
    | 'heart';


const getRandomColor = (): string =>{
    return '#' + Math.floor(Math.random() * 16777215).toString(16);
}

class Quadtree {
    boundary: Boundary;
    capacity: number;
    shapes: Shape[];
    divided: boolean;
    northwest?: Quadtree;
    northeast?: Quadtree;
    southwest?: Quadtree;
    southeast?: Quadtree;

    constructor(boundary: Boundary, capacity: number) {
        this.boundary = boundary;
        this.capacity = capacity;
        this.shapes = [];
        this.divided = false;
    }

    // Subdivide the quadtree
    subdivide(): void {
        const { x, y, width, height } = this.boundary;
        const nw: Boundary = { x, y, width: width / 2, height: height / 2 };
        const ne: Boundary = { x: x + width / 2, y, width: width / 2, height: height / 2 };
        const sw: Boundary = { x, y: y + height / 2, width: width / 2, height: height / 2 };
        const se: Boundary = { x: x + width / 2, y: y + height / 2, width: width / 2, height: height / 2 };

        this.northwest = new Quadtree(nw, this.capacity);
        this.northeast = new Quadtree(ne, this.capacity);
        this.southwest = new Quadtree(sw, this.capacity);
        this.southeast = new Quadtree(se, this.capacity);
        this.divided = true;
    }

    // Insert a shape into the quadtree
    insert(shape: Shape): boolean {
        if (!this.contains(shape)) {
            return false;
        }

        if (this.shapes.length < this.capacity) {
            this.shapes.push(shape);
            return...