46 lines
717 B
TypeScript
Raw Normal View History

2019-11-18 02:04:13 +00:00
export default function hexToHSL(hex: string) {
2019-11-17 09:25:14 +00:00
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
2019-06-18 08:47:01 +00:00
if(!result) {
return null
}
let r = parseInt(result[1], 16)
let g = parseInt(result[2], 16)
let b = parseInt(result[3], 16)
r /= 255
g /= 255
b /= 255
2019-11-17 09:25:14 +00:00
const max = Math.max(r, g, b)
const min = Math.min(r, g, b)
2019-06-18 08:47:01 +00:00
let h = 0
let s = 0
2019-11-17 09:25:14 +00:00
const l = (max + min) / 2
2019-06-18 08:47:01 +00:00
2019-11-18 02:04:13 +00:00
if(max === min) {
2019-06-18 08:47:01 +00:00
h = s = 0
} else {
2019-11-17 09:25:14 +00:00
const d = max - min
2019-06-18 08:47:01 +00:00
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}
}