Last active
August 26, 2021 13:55
-
-
Save erkobridee/263ace9c3509dc77cfed1938041b4e21 to your computer and use it in GitHub Desktop.
js transform hex color to hsl color
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 hexToHSL(hex) { | |
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); | |
let r = parseInt(result[1], 16); | |
let g = parseInt(result[2], 16); | |
let b = parseInt(result[3], 16); | |
(r /= 255), (g /= 255), (b /= 255); | |
let max = Math.max(r, g, b), min = Math.min(r, g, b); | |
let h, s, l = (max + min) / 2; | |
if (max == min) { | |
h = s = 0; // achromatic | |
} else { | |
const 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; | |
} | |
h = Math.round(360 * h); | |
s = Math.round(100 * s); | |
l = Math.round(100 * l); | |
return ({ h, s, l }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment