Skip to content

Instantly share code, notes, and snippets.

@toja
Last active May 26, 2016 13:42
Show Gist options
  • Save toja/53d21aadf3b8e2275fbf97c812292df1 to your computer and use it in GitHub Desktop.
Save toja/53d21aadf3b8e2275fbf97c812292df1 to your computer and use it in GitHub Desktop.
4096 colors - equal spaced (RGB cube)
license: gpl-3.0

4096 RGB-colors mapped to hue and luminace. 16 equal spaced values per axis.

Inspired by Visualizing Algorithms.

<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500;
// Create raster in the RGB-cube (16 x 16 x 16)
var a = d3.range(0, 255, 16).map(function (r) { return r + 8; })
var colors = cartesianProduct(a, a, a);
var sample = colorSampler(width, height);
var scaleWidth = d3.scale.linear()
.domain([0, 360])
.range([0, width]);
var scaleHeight = d3.scale.linear()
.range([height, 0]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.timer(function() {
for (var i = 0; i < 10; ++i) {
var s = sample();
if (!s) return true;
svg.append("circle")
.attr("cx", s[0])
.attr("cy", s[1])
.attr("r", 0)
.style("fill", s[2])
.transition()
.attr("r", 4);
}
});
function colorSampler(width, height) {
var i = 0;
return function() {
if (++i > colors.length) return;
var c = colors[i - 1];
var rgb = d3.rgb(c[0], c[1], c[2]);
var hsl = rgb.hsl();
return [scaleWidth(hsl.h), scaleHeight(hsl.l), rgb.toString()];
};
}
// http://stackoverflow.com/questions/15298912/javascript-generating-combinations-from-n-arrays-with-m-elements
function cartesianProduct() {
var r = [], arg = arguments, max = arg.length-1;
function helper(arr, i) {
for (var j=0, l=arg[i].length; j<l; j++) {
var a = arr.slice(0); // clone arr
a.push(arg[i][j]);
if (i==max)
r.push(a);
else
helper(a, i+1);
}
}
helper([], 0);
return r;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment