Skip to content

Instantly share code, notes, and snippets.

@LiuJi-Jim
Last active December 23, 2015 04:39
Show Gist options
  • Save LiuJi-Jim/6582154 to your computer and use it in GitHub Desktop.
Save LiuJi-Jim/6582154 to your computer and use it in GitHub Desktop.
JavaScript HSL color generator
<html>
<head>
<style>
#list {
}
.item {
width:15px;
height:10px;
overflow:hidden;
float:left;
}
</style>
</head>
<body>
<div id="list"></div>
<script>
function hex2dec(hex){
var dec = hex.toString('16');
if (hex < 0x10) return '0' + dec;
return dec;
}
function mkColor(r, g, b){
return '#' + hex2dec(r) + hex2dec(g) + hex2dec(b);
}
function hsl2rgb(h, s, l){
var q;
if (l < 0.5) q = l * (1.0 + s);
else q = l + s - l * s;
var p = 2.0 * l - q;
h = h / 360;
if (h == 1) h = 0;
function norm(v){
if (v < 0) return v + 1.0;
if (v >= 1) return v - 1.0;
return v;
}
function calc(v){
if (v * 6.0 < 1) return p + (q - p) * 6.0 * v;
else if (v * 2.0 < 1) return q;
else if (v * 3.0 < 2) return p + (q - p) * (2.0 / 3.0 - v) * 6.0;
else return p;
}
function norm2(v){
v = Math.floor(v * 256);
if (v < 0) v = 0;
if (v > 255) v = 255;
return v;
}
var r = norm2(calc(norm(h + 1.0 / 3.0))),
g = norm2(calc(norm(h))),
b = norm2(calc(norm(h - 1.0 / 3.0)));
return [r, g, b];
}
var list = document.getElementById('list');
function add(rgb){
var div = document.createElement('div');
div.className = 'item';
div.style.backgroundColor = rgb;
list.appendChild(div);
}
var hmin = 0, hmax = 360, hstep = 5,
smin = 0.5, smax = 0.8, sstep = 0.1,
lmin = 0.5, lmax = 0.7, lstep = 0.1;
list.style.width = 15 * ((smax - smin) / sstep + 1) * ((lmax - lmin) / lstep + 1) + 'px';
for (var h=hmin; h<=hmax; h+=hstep){
for (var s=smin; s<=smax; s+=sstep){
for (var l=lmin; l<=lmax; l+=lstep){
var arr = hsl2rgb(h, s, l);
var rgb = mkColor(arr[0], arr[1], arr[2]);
add(rgb);
var hsl = 'hsla(' + [h, s * 100 + '%', l * 100 + '%', 1].join(', ') + ')';
//add(hsl);
}
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment