Last active
November 9, 2018 10:35
-
-
Save bhoomit/9b9b67cb208fedad1b93 to your computer and use it in GitHub Desktop.
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
| function rgbToHsl(r, g, b){ | |
| r /= 255, g /= 255, b /= 255; | |
| var max = Math.max(r, g, b), min = Math.min(r, g, b); | |
| var h, s, l = (max + min) / 2; | |
| if(max == min){ | |
| h = s = 0; // achromatic | |
| }else{ | |
| var d = max - min; | |
| s = l > 0.5 ? d / (2 - max - min) : d / (max + min); | |
| switch(max){ | |
| case r: h = (g - b) / d + (g < b ? 6 : 0); break; | |
| case g: h = (b - r) / d + 2; break; | |
| case b: h = (r - g) / d + 4; break; | |
| } | |
| h /= 6; | |
| } | |
| return [h, s, l]; | |
| } | |
| 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; | |
| } | |
| function hexToHsl(hex){ | |
| var rgbDict = hexToRgb(hex); | |
| return rgbToHsl(rgbDict.r, rgbDict.g, rgbDict.b); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment