simple clustering2.5

by jpeter06

HTML

<canvas id="pcanvas" class="canvas">
  sin canvas
</canvas>

CSS

html, body{
  margin:0px;
  padding:0px;
  width:100%;
  height:100%;
  overflow:hidden;
}

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 nump = 50;
var points=[];
var clusters=[];
var dist= 50;

var canvas = document.getElementById("pcanvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
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 genNextPos(){
	var p;
  var p2;
  var vx;
  var vy;
  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;
      	vx=p.nx-p2.nx;
        vy=p.ny-p2.ny;
        p.fx-= vx*dp;
        p.fy-= vy*dp;
        p2.fx += vx*dp;
        p2.fy += vy*dp;
      }
    }
  }
  
  for(var i=0; i< points.length; i++){
  	points[i].nx=points[i].fx;
  	points[i].ny=points[i].fy;
  }
}



function initPoints(){
   points=[];
   clusters=[];
   // Generamos puntos
  for(var i=0; i< nump; i++){
   var p ={x:cwidth*Math.random(), 
    						y:cheight*Math.random()};
    p.nx=p.x;//Next
    p.ny=p.y;
    p.fx=p.x; //Future
    p.fy=p.y;
    points.push(p);
  }
}

function doEndIteration(){
	doIteration(true)
}

function doIteration(final){
   ctx.clearRect(0, 0, canvas.width,...