Created
June 15, 2022 11:45
-
-
Save thybzi/9e4cf3864a415ffa8e485eca5db89e05 to your computer and use it in GitHub Desktop.
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
/** | |
* Convert #1a2b3c to { h: 210, g: 40, b: 17 } | |
* @param {string} hex | |
* @returns {*} | |
* @see https://stackoverflow.com/q/46432335/3027390 | |
* @see https://stackoverflow.com/a/46432866/3027390 | |
*/ | |
function hexToHsl(hex) { | |
const rgb = _f.hexToRgb(hex); | |
const r = rgb.r / 255; | |
const g = rgb.g / 255; | |
const b = rgb.b / 255; | |
const max = Math.max(r, g, b); | |
const min = Math.min(r, g, b); | |
let h; | |
let s; | |
let l = (max + min) / 2; | |
if (max === min) { | |
// Achromatic | |
h = s = 0; | |
} else { | |
const delta = max - min; | |
// Calculate hue | |
switch (max) { | |
case r: | |
h = ((g - b) / delta) + ((g < b) ? 6 : 0); | |
break; | |
case g: | |
h = ((b - r) / delta) + 2; | |
break; | |
case b: | |
h = ((r - g) / delta) + 4; | |
break; | |
} | |
h /= 6; | |
// Calculate saturation | |
if (l > 0.5) { | |
s = delta / (2 - max - min); | |
} else { | |
s = delta / (max + min); | |
} | |
} | |
h = Math.round(h * 360); | |
s = Math.round(s * 100); | |
l = Math.round(l * 100); | |
return { | |
h: h, | |
s: s, | |
l: l, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment