var canvas = document.querySelector("canvas"),
out = document.querySelector("output"),
ctx = canvas.getContext("2d"),
w = canvas.width,
h = canvas.height,
cells = 9, sx = w / cells, sy = h / cells, x, y
// random color boxes (will be pretty even in count):
for(y = 0; y < h; y += sy) {for(x = 0; x < w; x += sx) {
ctx.fillStyle = "hsl(" + (360*Math.random()) + ",60%,50%)";
ctx.fillRect(x|0, y|0, Math.ceil(sx), Math.ceil(sy));
}}
// get bitmap
var idata = ctx.getImageData(0, 0, w, h), // area to analyze
buffer32 = new Uint32Array(idata.data.buffer), // use 32-bit buffer (faster)
i, len = buffer32.length,
stats = {};
for(i = 0; i < len; i++) {
var key = "" + (buffer32[i] & 0xffffff); // filter away alpha channel
if (!stats[key]) stats[key] = 0; // init this color key
stats[key]++ // count it..
}
// you can loop through the keys and convert the key into RGB values later
out.innerHTML = JSON.stringify(stats);
// convert first key:
var keys = Object.keys(stats),
count = keys.length,
key = keys[0]
var r = key & 0xff, g = (key & 0xff00)>>>8, b = (key & 0xff0000)>>>16;
alert("First key: " + r + "," + g + "," + b + "=" + stats[key] +
"\nUnique colors: " + count);
<canvas></canvas><br><output></output>