Skip to content

Instantly share code, notes, and snippets.

@NerdyDeedsLLC
Created June 29, 2023 01:25
Show Gist options
  • Save NerdyDeedsLLC/562cbd8a048266ffc766d0dbf11e0378 to your computer and use it in GitHub Desktop.
Save NerdyDeedsLLC/562cbd8a048266ffc766d0dbf11e0378 to your computer and use it in GitHub Desktop.
function RGBToHSL(HEXA, invert=false) {
let [r,g,b,a]=HEXA.replace(/^#?(?:(?:(..)(..)(..)(..)?)|(?:(.)(.)(.)(.)?))$/, '$1$5$5$2$6$6$3$7$7$4$8$8').match(/(..)/g).map(rgb=>parseInt('0x'+rgb)/255),
cmin = Math.min(r,g,b),
cmax = Math.max(r,g,b),
delta = cmax - cmin,
h = 0,
s = 0,
l = 0
i = invert? -100 : 0;
if (!delta) h = 0;
else if (cmax == r) h = ~~((((g - b) / delta) % 6) * 60);
else if (cmax == g) h = ~~((((b - r) / delta) + 2) * 60);
else h = ~~((((r - g) / delta) + 4) * 60);
h = (h<0) ? h+360 : h;
l = (cmax + cmin) / 2;
s = delta == 0 ? 0 : delta / (1 - Math.abs(2 * l - 1));
s = +(s * 100).toFixed(1);
l = +(l * 100).toFixed(1);
return "hsl(" + h + "," + s + "%," + Math.abs(i + l) + "%)";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment