Skip to content

Instantly share code, notes, and snippets.

@LiuJi-Jim
Created September 16, 2013 17:03
Show Gist options
  • Save LiuJi-Jim/6583455 to your computer and use it in GitHub Desktop.
Save LiuJi-Jim/6583455 to your computer and use it in GitHub Desktop.
JavaScript HSV 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 hsv2rgb(h, s, v){
var R, G, B;
if (s == 0){
R = G = B = v;
}else{
var h2 = h / 60;
var i = Math.floor(h2),
f = h2 - i,
p = v * (1 - s),
q = v * (1 - s * f),
t = v * (1 - s * (1 - f));
if (i == 0 || i == 6){
R = v; G = t; B = p;
}
if (i == 1){
R = q; G = v; B = p;
}
if (i == 2){
R = p; G = v; B = t;
}
if (i == 3){
R = p; G = q; B = v;
}
if (i == 4){
R = t; G = p; B = v;
}
if (i == 5){
R = v; G = p; B = q;
}
}
function norm2(v){
v = Math.floor(v * 256);
if (v < 0) v = 0;
if (v > 255) v = 255;
return v;
}
return [
norm2(R),
norm2(G),
norm2(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.7, smax = 1.0, sstep = 0.1,
vmin = 0.8, vmax = 1.0, vstep = 0.1;
list.style.width = 15 * ((smax - smin) / sstep + 1) * ((vmax - vmin) / vstep + 1) + 'px';
for (var h=hmin; h<=hmax; h+=hstep){
for (var s=smin; s<=smax; s+=sstep){
for (var v=vmin; v<=vmax; v+=vstep){
var arr = hsv2rgb(h, s, v);
var rgb = mkColor(arr[0], arr[1], arr[2]);
add(rgb);
}
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment