Skip to content

Instantly share code, notes, and snippets.

@jahan-addison
Last active August 29, 2015 14:09
Show Gist options
  • Save jahan-addison/849a7605a681da911bb9 to your computer and use it in GitHub Desktop.
Save jahan-addison/849a7605a681da911bb9 to your computer and use it in GitHub Desktop.
Non-deterministic tetrad color set for visual applications
var Tetrad = function() {
this.degrees = 30;
this.colors;
};
Tetrad.prototype = (function() {
/**
* Private
*/
/* Turn an HSV color format into the computable RGB */
var toRGB = function(color) {
var r, g, b, i, f, p, q, t;
var h = color[0] / 100,
s = color[1],
v = color[2];
i = Math.floor(h * 6);
f = h * 6 - i;
p = v * (1 - s);
q = v * (1 - f * s);
t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0: r = v, g = t, b = p; break;
case 1: r = q, g = v, b = p; break;
case 2: r = p, g = v, b = t; break;
case 3: r = p, g = q, b = v; break;
case 4: r = t, g = p, b = v; break;
case 5: r = v, g = p, b = q; break;
}
return [
Math.floor(r * 255),
Math.floor(g * 255),
Math.floor(b * 255)
].reduce(function(a, b) {
return a.toString(16) + b.toString(16);
});
};
/* Non-deterministically determine a new base color in HSV */
var base = function() {
var h = Math.floor(Math.random() * (360 - 1)) + 1,
s = 68 / 100,
v = 78 / 100;
return [h, s, v];
};
/* Generate a Tetrad set */
var generate = function() {
var first = base(),
firstAnalogous = (first[0] + this.degrees) % 360,
secondComplementary = (first[0] + 180) % 360,
secondAnalogous = (secondComplementary + this.degrees) % 360;
return [first,
[firstAnalogous, first[1], first[2]],
[secondComplementary, first[1], first[2]],
[secondAnalogous, first[1], first[2]]];
};
/**
* Public
*/
return {
Constructor: Tetrad,
/* An index between 0 and 3 */
get: function(index) {
if (!this.colors) {
this.colors = generate.call(this);
}
var a = toRGB(this.colors[0]), b = toRGB(this.colors[1]);
var c = toRGB(this.colors[2]), d = toRGB(this.colors[3]);
switch(index) {
case 0: return a;
case 1: return b;
case 2: return c;
case 3: return d;
}
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment