Skip to content

Instantly share code, notes, and snippets.

@nblenke
Created January 31, 2014 17:19
Show Gist options
  • Save nblenke/8737110 to your computer and use it in GitHub Desktop.
Save nblenke/8737110 to your computer and use it in GitHub Desktop.
function RgbToHsv(r, g, b) {
var min = Math.min(r, g, b),
max = Math.max(r, g, b),
delta = max - min,
h, s, v = max;
v = Math.floor(max / 255 * 100);
if (max == 0) return {h: 0, s: 0, v: 0};
s = Math.floor(delta / max * 100);
var deltadiv = delta == 0 ? 1 : delta;
if( r == max ) h = (g - b) / deltadiv;
else if(g == max) h = 2 + (b - r) / deltadiv;
else h = 4 + (r - g) / deltadiv;
h = Math.floor(h * 60);
if( h < 0 ) h += 360;
return { h: h, s:s, v:v }
}
function HsvToRgb(h, s, v) {
h = h / 360;
s = s / 100;
v = v / 100;
if (s == 0)
{
var val = Math.round(v * 255);
return {r:val,g:val,b:val};
}
hPos = h * 6;
hPosBase = Math.floor(hPos);
base1 = v * (1 - s);
base2 = v * (1 - s * (hPos - hPosBase));
base3 = v * (1 - s * (1 - (hPos - hPosBase)));
if (hPosBase == 0) {red = v; green = base3; blue = base1}
else if (hPosBase == 1) {red = base2; green = v; blue = base1}
else if (hPosBase == 2) {red = base1; green = v; blue = base3}
else if (hPosBase == 3) {red = base1; green = base2; blue = v}
else if (hPosBase == 4) {red = base3; green = base1; blue = v}
else {red = v; green = base1; blue = base2};
red = Math.round(red * 255);
green = Math.round(green * 255);
blue = Math.round(blue * 255);
return {r:red,g:green,b:blue};
}
function RgbComponentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function RgbToHex(r, g, b) {
return "#" + RgbComponentToHex(r) + RgbComponentToHex(g) + RgbComponentToHex(b);
}
function HexToRgb(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment