Skip to content

Instantly share code, notes, and snippets.

@ibrechin
Created April 25, 2012 11:13
Show Gist options
  • Save ibrechin/2489005 to your computer and use it in GitHub Desktop.
Save ibrechin/2489005 to your computer and use it in GitHub Desktop.
Generate evenly distributed spectrum in JavaScript
hslToRgb = function(_h, s, l) {
var h = Math.min(_h, 359)/60;
var c = (1-Math.abs((2*l)-1))*s;
var x = c*(1-Math.abs((h % 2)-1));
var m = l - (0.5*c);
var r = m, g = m, b = m;
if (h < 1) {
r += c, g = +x, b += 0;
} else if (h < 2) {
r += x, g += c, b += 0;
} else if (h < 3) {
r += 0, g += c, b += x;
} else if (h < 4) {
r += 0, g += x, b += c;
} else if (h < 5) {
r += x, g += 0, b += c;
} else if (h < 6) {
r += c, g += 0, b += x;
} else {
r = 0, g = 0, b = 0;
}
return 'rgb(' + Math.floor(r*255) + ', ' + Math.floor(g*255) + ', ' + Math.floor(b*255) + ')';
}
createSpectrum = function(length) {
var colors = [];
// 270 because we don't want the spectrum to circle back
var step = 270/length;
for (var i = 1; i <= length; i++) {
var color = hslToRgb((i)*step, 0.5, 0.5);
colors.push(color);
}
return colors;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment