Skip to content

Instantly share code, notes, and snippets.

@nicholaswmin
Last active April 16, 2016 18:10
Show Gist options
  • Save nicholaswmin/3834b42219d5c127a0ed to your computer and use it in GitHub Desktop.
Save nicholaswmin/3834b42219d5c127a0ed to your computer and use it in GitHub Desktop.
Clustering Paper.js Elements together using the K-means algorithm.
/**
* Clusters a number of Paper Elements as Paper Groups.
* Clustering is based on distance between elements,
* using K-means clustering.
* - This method DOES NOT preserve z-order of items, so use with caution
*
*
* - Dependent on clusterfck.js.
* See: https://github.com/NathanEpstein/clusters
* and download browser .js file.
*
* @param {Array} - items - Array of Paper Items.
* @param {Number} - clusterNum - Amount of clusters to create
*
* @return {Array} - Array of Paper Groups
*
* Authors:
* - Nicholas Kyriakides, @nicholaswmin
*/
function clusterKMeans(items,clusterNum) {
// min clusters num is the amount of items
if(items.length < clusterNum) {
clusterNum = items.length;
}
var pointsArr = [];
for (var i = 0; i < items.length; i++) {
pointsArr.push([items[i].position.x,items[i].position.y,items[i].id]);
}
var clusters = clusterfck.kmeans(pointsArr, clusterNum);
var groupsArr = [];
for (var i = 0; i < clusters.length; i++) {
var group = new paper.Group();
for (var k = 0; k < clusters[i].length; k++) {
for (var l = 0; l < items.length; l++) {
if(items[l].id === clusters[i][k][2]) {
group.addChild(items[l])
}
}
}
groupsArr.push(group.clone());
group.remove()
}
return groupsArr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment