Created
June 11, 2015 23:43
-
-
Save clngn/e44abf60437c310b827c to your computer and use it in GitHub Desktop.
RGB, HSV, HEX
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function() { | |
var hex = $('#hex').text(); | |
console.log(hex); | |
var rgb = hex2rgb(hex); | |
console.log(rgb); | |
var hsv = rgb2hsv(rgb); | |
console.log(hsv); | |
var rgb2 = hsv2rgb(hsv); | |
console.log(rgb2); | |
var hex2 = rgb2hex(rgb2); | |
console.log(hex2); | |
}); | |
function hex2rgb(hex) { | |
return { | |
'r': parseInt(hex.substr(1,2), 16), | |
'g': parseInt(hex.substr(3,2), 16), | |
'b': parseInt(hex.substr(5,2), 16) | |
}; | |
} | |
function rgb2hsv(rgb) { | |
var max = Math.max(rgb['r'], rgb['g'], rgb['b']); | |
var min = Math.min(rgb['r'], rgb['g'], rgb['b']); | |
var v = max * 100 / 255; | |
var s = (max - min) * 100 / max; | |
var h = 0; | |
switch (max) { | |
case rgb['r']: | |
h = 60 * (rgb['g'] - rgb['b']) / (max - min); | |
break; | |
case rgb['g']: | |
h = 60 * (((rgb['b'] - rgb['r']) / (max - min)) + 2); | |
break; | |
case rgb['b']: | |
h = 60 * (((rgb['r'] - rgb['g']) / (max - min)) + 4); | |
break; | |
} | |
if (h < 0) { | |
h += 360; | |
} | |
return { | |
'h': Math.round(h), | |
's': Math.round(s), | |
'v': Math.round(v) | |
}; | |
} | |
function hsv2rgb(hsv) { | |
var h = hsv['h']; | |
var s = hsv['s'] / 100; | |
var v = hsv['v'] / 100; | |
var r = 0; | |
var g = 0; | |
var b = 0; | |
if (s == 0) { | |
return { | |
'r': v * 255, | |
'g': v * 255, | |
'b': v * 255 | |
}; | |
} | |
var hi = Math.floor(h / 60) % 6; | |
var f = (h / 60) - Math.floor(h / 60); | |
var p = v * (1 - s); | |
var q = v * (1 - (f * s)); | |
var t = v * (1 - ((1 - f) * s)); | |
switch (hi) { | |
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 { | |
'r': Math.floor(r * 255), | |
'g': Math.floor(g * 255), | |
'b': Math.floor(b * 255) | |
}; | |
} | |
function rgb2hex(rgb) { | |
return '#' | |
+ rgb['r'].toString(16) | |
+ rgb['g'].toString(16) | |
+ rgb['b'].toString(16); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment