JS K-Mean

K-mean algorithm by JavaScript.

by Tinytsunami

HTML

<div id="demo">
  <canvas width="400px" height="400px"></canvas>
  <br />
  * Click screen to add cluster kernel
  <br />
  <button>Add Some Data</button>
  <button>Clear Data</button>
</div>

CSS

body {
  color: #ffffff;
  background: #20262e;
  font-family: monospace, sans-serif;
}

#demo {
  padding: 5px;
}

#demo canvas {
  border: solid 1px #ffffff;
}

#demo button {
  color: #ffffff;
  background: #20262e;
  border: 1px solid #ffffff;
  margin-top: 4px;
  outline: none;
}

#demo button:hover {
  color: #20262e;
  background: #ffffff;
  border: 1px solid #ffffff;
}

JavaScript

(function() {
  /* get elements */
  let root = document.getElementById("demo");
  let canvas = root.getElementsByTagName("canvas")[0];
  let create = root.getElementsByTagName("button")[0];
  let clear = root.getElementsByTagName("button")[1];
  let context = canvas.getContext("2d");
  
  /* define variables */
  let width = 400;
  let height = 400;
  let data = [];
  let core = [];
	let noneClusterColor = "#ffffff";

  /* initialize canvas */
  canvas.width = width;
  canvas.height = height;
  context.translate(width/2, height/2);
  
  /* refresh canvas */
  let refresh = function() {
    context.clearRect(-width/2, -height/2, width, height);
    for(let i in data) {
      let x = data[i][0];
      let y = data[i][1];
      let c = data[i][2];
      let color = (c == -1) ? noneClusterColor : core[c][2];
      context.beginPath();
      context.strokeStyle = color;
      context.arc(x, y, 3, 0,  Math.PI*2);
      context.stroke();
      context.closePath();
    }
    for(let i in core) {
      let x = core[i][0];
      let y = core[i][1];
      let color = core[i][2];
      context.beginPath();
      context.strokeStyle = color;
      context.arc(x, y, 3, 0,  Math.PI*2);
      context.stroke();
      context.closePath();
    }
  };

  /* get random number in [a, b] */
  let rand = function(a, b) {
    return Math.floor((b - a) * Math.random()) + a;
  };
  
  let randColor = function() {
    return "#" + Math.random().toString(16).substr(-6);
  };
  
  /* add data */
  let bias = 30;
  create.onclick = function() {
    let x = rand(-width/2, width/2);
    let y = rand(-height/2, height/2);
    for(let i = 0; i < 20; i++) {
      x += rand(-bias, bias);
      y += rand(-bias, bias);
      data.push([x, y, -1]);
    }
    refresh();
  };

  /* add cluster kernel */
  canvas.onmousedown = function(e) {
    let x = e.offsetX - width/2;
    let y = e.offsetY - height/2;
    let c = randColor();
    core.push([x, y, c]);
    refresh();
  };
  
  /* clear all*/
 ...