rgb2hsl · JavaScript Function to Convert Colors from RGB to HSL
function rgb2hsl (r, g, b) {
const r_ratio = r / 255
const g_ratio = g / 255
const b_ratio = b / 255
const min = Math.min(r_ratio, b_ratio, g_ratio)
const max = Math.max(r_ratio, b_ratio, g_ratio)
const l_ratio = (min + max) / 2
const range = max - min
if (range === 0) return { h: 0, s: 0, l: 0 }
const h_ratio = (() => {
if (max === r_ratio) return (g_ratio - b_ratio) / range
if (max === g_ratio) return 2 + (b_ratio - r_ratio) / range
return 4 + (r_ratio - g_ratio) / range
})()
const s_range = Math.min(l_ratio, 1 - l_ratio)
return {
h: ((h_ratio + 6) % 6) * 60,
s: (max - min) / (2 * s_range) * 100,
l: l_ratio * 100,
}
}
Last updated 3 days ago.