Convex hull natural state

Burak Kanber

by Matthew Vasallo

HTML

<canvas id="canvas" height="400" width="400"></canvas>

CSS

canvas {
            display:block;
            margin:10px auto;
            border:1px solid black;
        }

JavaScript

/*
 * This is NOT free software. You may learn from and experiment with this code but you may not redistribute it or use it in any commercial application without the explicit prior consent of the author.
 * Burak Kanber
 * [email protected]
 * October 2012
 */

var canvas; 
var ctx;
var height = 400;
var width = 400;
var data = [];
for (var i = 0; i < 100; i++){
    var x = Math.random() * 20;
    var y = Math.random() * 20;
    data.push([x,y]);
}

// var data = [
//   // [1, 2],
//   // [2, 1],
//   // [2, 4], 
//   // [1, 3],
//   // [2, 2],
//   // [3, 1],
//   // [1, 1],

//   [7, 3],
//   [8, 2],
//   [6, 4],
//   [7, 4],
//   [8, 1],
//   [9, 2],

//   // [10, 8],
//   // [9, 10],
//   // [7, 8],
//   // [7, 9],
//   // [8, 11],
//   // [9, 9],
// ];



var means = [];
var assignments = [];
var dataExtremes;
var dataRange;
var drawDelay = 2;

var maxHeat = 0;
var heatdecay = 0.001;
var heat = maxHeat;

var colours = [];

/* Convex hull code */


// >0 : counter clockwise turn
// <0 : clockwise turn
// 0 : collinear
function ccw (p1, p2, p3) {
  return (p2[0] - p1[0])*(p3[1] - p1[1]) - (p2[1] - p1[1])*(p3[0] - p1[0]);
};

function swap(a, i1, i2){
  var t = a[i1];
  a[i1] = a[i2];
  a[i2] = t;
};

function convexHull(points){
  var i;
  var n = points.length;
  var hull = [];
  // Start with the point with the lowest y coord:
  var lowest = 0;
  for (i=1;i<n;i++){
    if(points[i][1] < points[lowest][1]){
      lowest = i;
    } else if(points[i][1] === points[lowest][1]){
      if(points[i][0] < points[lowest][0]){
        lowest = i;
      }
    }
  }

  // Need to sort the points by the angle they and the starting point make with the x-axis.
  var p = points[lowest];
  var other = points.slice(); //Copy the array of points.
  other.splice(lowest, 1); //Remove the lowest
  other.sort(function(p1, p2){
    var ap1 = Math.atan2(p1[1]-p[1], p1[0] - p[0]);
    var ap2 = Math.atan2(p2[1]-p[1], p2[0] - p[0]);
    return ap1 - ap2;
  });

  hull =...