JSFiddle - React, Tailwind, and code Playground
by electronoob
HTML
<canvas id="c" width="800px" height="800px"></canvas>
CSS
canvas {
//width: 800px;
//height: 800px;
image-rendering: optimizeSpeed;
image-rendering: -moz-crisp-edges;
image-rendering: -o-crisp-edges;
image-rendering: -webkit-optimize-contrast;
image-rendering: pixelated;
image-rendering: optimize-contrast;
-ms-interpolation-mode: nearest-neighbor;
margin: 10px;
border: 2px solid #000;
}
JavaScript
//quadtree
var growth = 500;
var draw = 1;
Q = new quadtree(0,0,100,100);
for(var i=0; i<growth; i++){
Q.insert(new Vector(gra(),gra()));
}
function gra() {
return Math.random() * 100;
}
function quadtree (x,y,width,height) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.max_points_per_quad = 4;
this.insert = function (v) {
this.root.insert(v);
};
this.root = new quad(0, 0, width, height, this.max_points_per_quad, "#fff");
this.getQuad = function (v) {
return this.root.getQuad(v);
}
}
function quad(x, y, width, height, max_points_per_quad, color) {
this.x = x?x:0;
this.y = y?y:0;
this.w = width?width:0;
this.h = height?height:0;
this.max_points_per_quad = max_points_per_quad;
this.count = 0;
this.full = false;
this.color = color?color:"#000";
this.inRange=(v)=>{
return !((v.x<this.x) || (v.x>this.x+this.w) || (v.y<this.y) || (v.y>this.y+this.h));
};
this.getQuad=(v)=>{
if(this.inRange(v)) {
if (this.full) {
if(this.tree.NW.inRange(v)) { return this.tree.NW.getQuad(v); }
if(this.tree.NE.inRange(v)) { return this.tree.NE.getQuad(v); }
if(this.tree.SE.inRange(v)) { return this.tree.SE.getQuad(v); }
if(this.tree.SW.inRange(v)) { return this.tree.SW.getQuad(v); }
} else {
return this;
}
} else {
return false;
}
};
// couldnt think of a better name
this.isPresent = (v) => {
for(var point of this.tree.points) {
if ((v.x === point.x) && (v.y === point.y)) {
return true;
}
}
return false;
}
/*
[NW][NE]
[SW][SE]
*/
this.tree = {
NW: null,
NE: null,
SE: null,
SW: null,
points: [],
};
this.split = ()=> {
this.full = true;
this.tree.NW = new quad(this.x, this.y, this.w/2, this.h/2, this.max_points_per_quad, "#fff");
this.tree.NE = new quad(this.x+this.w/2, this.y, this.w/2, ...