Skip to content

Instantly share code, notes, and snippets.

@romsson
Last active November 8, 2018 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romsson/a298e4ffe5b1842a7409ae5926b5042b to your computer and use it in GitHub Desktop.
Save romsson/a298e4ffe5b1842a7409ae5926b5042b to your computer and use it in GitHub Desktop.
Categorize colors venn diagram
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
canvas {
image-rendering: pixelated;
}
</style>
</head>
<body>
<script>
// Feel free to change or delete any of the code you see in this editor!
var width = 800,
height = 600;
var canvas = d3.select('body')
.append('canvas')
.attr('width', width)
.attr('height', height);
var ctx = canvas.node().getContext('2d');
var r = 100;
ctx.clearRect(0, 0, width, height);
ctx.globalAlpha = 0.5;
// does not seem to work https://stackoverflow.com/questions/195262/can-i-turn-off-antialiasing-on-an-html-canvas-element
ctx.imageSmoothingEnabled = false;
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(150, 150, r, 0, 2*Math.PI);
ctx.fill();
ctx.fillStyle = 'green';
ctx.beginPath();
ctx.arc(250, 150, r, 0, 2*Math.PI);
ctx.fill();
ctx.fillStyle = 'blue';
ctx.beginPath();
ctx.arc(200, 250, r, 0, 2*Math.PI);
ctx.fill();
// Uint8ClampedArray(1920000)
var imageData = ctx.getImageData(0, 0, width, height);
var pixels = imageData.data;
var colors = []
function count() {
for (var i = 0, il = pixels.length; i < il; i += 4) {
var color = pixels[i] + "-" + pixels[i+1] + "-" + pixels[i+2]
if(typeof(colors[color]) === "undefined") {
colors[color] = 0;
}
typeof(colors[color])++
}
// Put pixels back into canvas
ctx.putImageData(imageData, 0, 0);
}
count();
var c = d3.values(colors)
console.log(c.sort(d3.descending))
console.log(colors)
// export as csv
// https://gist.github.com/cmbaughman/586fd115b627e0a355553015ad5f0576
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment