Created
April 13, 2015 16:05
-
-
Save kjbrum/ff48c95f425524beee7a to your computer and use it in GitHub Desktop.
Convert an RGB color value to HSL
This file contains hidden or 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
/** | |
* Convert an RGB color value to HSL | |
* | |
* @param Number r The red color value (0-255) | |
* @param Number g The green color value (0-255) | |
* @param Number b The blue color value (0-255) | |
* @return Array The HSL representation | |
*/ | |
function rgbToHsl(r, g, b){ | |
r /= 255, g /= 255, b /= 255; | |
var max = Math.max(r,g,b), | |
min = Math.min(r,g,b), | |
h, s, | |
l = (max + min) / 2 ; // Calculate l | |
if(max == min) { | |
h = s = 0; // Grayscale | |
} else { | |
var d = max - min; | |
s = l < 0.5 ? d / (max + min) : d / (2.0 - d); // Calculate s | |
// Calculate h | |
switch(max) { | |
case r: h = (g - b) / d; break; | |
case g: h = 2.0 + (b - r) / d; break; | |
case b: h = 4.0 + (r - g) / d; break; | |
} | |
} | |
h = Math.round(h * 60); | |
s = Math.round(s * 100); | |
l = Math.round(l * 100); | |
if(h<0) h += 360; | |
return [h, s, l]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment