simple clustering2
by jpeter06
HTML
<canvas id="pcanvas" width="400" height="400">
sin canvas
</canvas>
CSS
html, body{
margin:0px;
padding:0px;
width:100%;
height:100%;
overflow:hidden;
}
canvas{
}
JavaScript
/*
- Iterativelly move over all points, and move toward nearest
- Find all points within a certain radius around that point.
- Form a new cluster with the nearby points.
- Choose a new point that isn’t part of a cluster, and repeat until we have visited all the points.*/
var canvas = document.getElementById("pcanvas");
var cwidth = canvas.width;
var cheight = canvas.height;
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#ffaa22";
// That's how you draw a point //
function point(x, y, r,ctx,text){
ctx.beginPath();
ctx.arc(x, y, r, 0, 2 * Math.PI, false);
ctx.fill();
}
function text(x, y, text,ctx){
ctx.beginPath();
ctx.fillText(text, x, y);
ctx.fill();
}
function distPoints(p1, p2){
return Math.sqrt((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y));
}
function distPointsN(p1, p2){
return Math.sqrt((p1.nx-p2.nx)*(p1.nx-p2.nx) + (p1.ny-p2.ny)*(p1.ny-p2.ny));
}
function genClusters(){
var p=null;
var tratados=[];
for(var i=0; i< points.length; i++){
p=points[i];
if(!tratados.includes(p)){
//Lo usamos como cluster, buscamos cercanos
var cluster=[];
clusters.push(cluster);
cluster.push(p);
tratados.push(p);
//Buscamos cercanos
for(var j=0 ; j < points.length ; j++){
var p2=points[j];
if(!tratados.includes(p2) && distPoints(p,p2)< 70){
cluster.push(p2);
tratados.push(p2);
}
}
}
}
console.log("num clusters:"+clusters.length);
}
function centerCluster(cluster){
var cx = 0.0;
var cy = 0.0;
var l = cluster.length;
for(var i=0; i<l; i++){
cx += cluster[i].x;
cy += cluster[i].y;
}
var r = { x:(cx/l), y:( cy/l)};
return r;
}
function genNextPos(){
var p;
var p2;
var vx;
var vy;
var dist=50;
var factor=0.09;
var dp=1;
for(var i=0; i< points.length; i++){
p=points[i];
for(var j=0 ; j < points.length ; j++){
p2=points[j];
dp = distPointsN(p,p2);
if(dp< dist){
dp=factor;
...