html5 canvas可视化集群

时间:2014-12-11 08:02:17

标签: html5 canvas cluster-analysis

我的canvas元素中有一组点。说,像这样:

enter image description here

我正在处理群集,所有这些点都属于一个群集。所以我必须以某种方式连接它们。连接它们的想法是什么?我的意思是,我只是在所有的poits之间划线,我必须以某种方式选择将形成簇的边界的点。我只想更加用户友好。也许一个解决方案可能是找到最小生成树并可视化它?你能提出什么建议?问题不是关于实施细节,而是关于如何做到这一点。

1 个答案:

答案 0 :(得分:1)

以下是如何计算随机圈的边界框:



// canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

// the radius of each circle
var radius=4;

// generate 4 random points
var points=[];
for(var i=0;i<4;i++){
  var randomX=Math.max(radius,Math.min(cw,Math.random()*cw-radius));
  var randomY=Math.max(radius,Math.min(ch,Math.random()*ch-radius));   
  points.push({x:randomX,y:randomY});
}

// vars to hold the top-left & bottom-right points of the cluster's bounding box
var minX=1000000;
var minY=minX;
var maxX=-100000;
var maxY=maxX;

// calc the bounding box
for(var i=0;i<points.length;i++){

  var p=points[i];

  // calc the top-left & bottom-right of this circle's bounding box
  var xleft=p.x-radius;
  var xright=p.x+radius;
  var ytop=p.y-radius;
  var ybottom=p.y+radius;

  // expand the cluster's bounding box based on this circle's bounding box
  if(xleft<minX){minX=xleft;}
  if(xright>maxX){maxX=xright;}
  if(ytop<minY){minY=ytop;}
  if(ybottom>maxY){maxY=ybottom;}

  // draw this point
  ctx.beginPath();
  ctx.arc(p.x,p.y,radius,0,Math.PI*2);
  ctx.closePath();
  ctx.stroke();

}

// draw the cluster's bounding box
var width=maxX-minX;
var height=maxY-minY;
ctx.strokeRect(minX,minY,width,height);
&#13;
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
&#13;
<canvas id="canvas" width=300 height=300></canvas>
&#13;
&#13;
&#13;