colorizr
Version:
Manipulate colors like a boss
50 lines (41 loc) • 1.02 kB
text/typescript
import { addAlpha, extractAlpha } from '~/modules/alpha';
import hue2rgb from '~/modules/hue2rgb';
import { parseInput } from '~/modules/utils';
import { ConverterParameters, HSL, RGB } from '~/types';
/**
* Convert HSL to RGB.
*
* @param input - The HSL color object or tuple.
* @returns The RGB color object.
*/
export default function hsl2rgb(input: ConverterParameters<HSL>): RGB {
const value = parseInput(input, 'hsl');
const alpha = extractAlpha(input);
const h = value.h / 360;
const s = value.s / 100;
const l = value.l / 100;
let r;
let g;
let b;
let point;
let chroma;
if (s < 0.0001) {
r = l;
g = l;
b = l;
} else {
chroma = l < 0.5 ? l * (1 + s) : l + s - l * s;
point = 2 * l - chroma;
r = hue2rgb(point, chroma, h + 1 / 3);
g = hue2rgb(point, chroma, h);
b = hue2rgb(point, chroma, h - 1 / 3);
}
return addAlpha(
{
r: Math.round(r * 255),
g: Math.round(g * 255),
b: Math.round(b * 255),
},
alpha,
);
}