Skip to content

Instantly share code, notes, and snippets.

@toja
Last active June 3, 2016 09:54
Show Gist options
  • Save toja/6c42e89893dd84ab118d51e53bcd9a35 to your computer and use it in GitHub Desktop.
Save toja/6c42e89893dd84ab118d51e53bcd9a35 to your computer and use it in GitHub Desktop.
4096 Random Colors - Histogram (RGB)
height: 480
license: gpl-3.0
<!DOCTYPE html>
<meta charset="utf-8">
<script src="//d3js.org/d3.v3.min.js"></script>
<body>
<script>
var width = 960,
height = 480,
grid = [32,32],
space = 1.0,
numColors = 4096;
var binWidth = width / grid[0] - space * 2,
binHeight = height / grid[1] - space * 2;
var x = d3.scale.linear()
.domain([0, 360])
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xz = d3.range(0, width, width / grid[0]),
yz = d3.range(0, height, height / grid[1]);
var bins = yz.map(function(y) { return xz.map(function(x) { return { x: x, y: y, z: 0 }; }); });
var data = d3.nest()
.key(function(d) {return d.y;})
.entries(d3.merge(bins));
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var hist = svg.append("g")
var rows = hist.selectAll("g")
.data(data)
.enter().append("g")
rows.selectAll("rect")
.data(function(d) { return d.values; })
.enter().append("rect")
.attr("id", function (d) { return "x" + d.x + "y" + d.y; })
.attr("x", function (d) { return d.x + space; })
.attr("y", function (d) { return d.y + space; })
.attr("width", binWidth)
.attr("height", binHeight)
.style("fill", "#fff");
var dots = svg.append("g");
var sample = colorSampler(numColors);
d3.timer(function() {
var hsl = sample();
if (!hsl) return true;
var cx = x(hsl.h),
cy = y(hsl.l);
dots.append("circle")
.attr("cx", cx)
.attr("cy", cy)
.attr("r", 8)
.style("fill", hsl.toString())
.transition()
.attr("r", 0);
var col = Math.floor((cx / width) * grid[0]),
row = Math.floor((cy / height) * grid[1]),
bin = bins[row][col],
id = "x" + bin.x + "y" + bin.y;
bin.z += 8;
d3.select("#" + id)
.style("fill", d3.rgb(255 - bin.z, 255 - bin.z, 255 - bin.z).toString());
});
function colorSampler(numSamplesMax) {
var numSamples = 0;
return function() {
if (++numSamples > numSamplesMax) return;
do {
var hsl = d3.hsl(d3.rgb(
Math.floor(Math.random() * 256),
Math.floor(Math.random() * 256),
Math.floor(Math.random() * 256)
));
} while (!hsl.h);
return hsl;
};
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment