Skip to content

Instantly share code, notes, and snippets.

@xenozauros
Last active May 7, 2024 09:21
Show Gist options
  • Save xenozauros/f6e185c8de2a04cdfecf to your computer and use it in GitHub Desktop.
Save xenozauros/f6e185c8de2a04cdfecf to your computer and use it in GitHub Desktop.
Javascript: HEX to RGB to HSL
function hexToHSL(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
r = parseInt(result[1], 16);
g = parseInt(result[2], 16);
b = parseInt(result[3], 16);
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;
}
var HSL = new Object();
HSL['h']=h;
HSL['s']=s;
HSL['l']=l;
return HSL;
}
@jbender0
Copy link

jbender0 commented May 7, 2024

Awesome job! Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment