43 lines
1.0 KiB
JavaScript
43 lines
1.0 KiB
JavaScript
|
// Adapted from https://gist.github.com/mjackson/5311256
|
||
|
function hueToRgb(p, q, t) {
|
||
|
if (t < 0)
|
||
|
t += 1;
|
||
|
if (t > 1)
|
||
|
t -= 1;
|
||
|
if (t < 1 / 6)
|
||
|
return p + (q - p) * 6 * t;
|
||
|
if (t < 1 / 2)
|
||
|
return q;
|
||
|
if (t < 2 / 3)
|
||
|
return p + (q - p) * (2 / 3 - t) * 6;
|
||
|
return p;
|
||
|
}
|
||
|
function hslaToRgba({ hue, saturation, lightness, alpha }) {
|
||
|
hue /= 360;
|
||
|
saturation /= 100;
|
||
|
lightness /= 100;
|
||
|
let red = 0;
|
||
|
let green = 0;
|
||
|
let blue = 0;
|
||
|
if (!saturation) {
|
||
|
red = green = blue = lightness;
|
||
|
}
|
||
|
else {
|
||
|
const q = lightness < 0.5
|
||
|
? lightness * (1 + saturation)
|
||
|
: lightness + saturation - lightness * saturation;
|
||
|
const p = 2 * lightness - q;
|
||
|
red = hueToRgb(p, q, hue + 1 / 3);
|
||
|
green = hueToRgb(p, q, hue);
|
||
|
blue = hueToRgb(p, q, hue - 1 / 3);
|
||
|
}
|
||
|
return {
|
||
|
red: Math.round(red * 255),
|
||
|
green: Math.round(green * 255),
|
||
|
blue: Math.round(blue * 255),
|
||
|
alpha,
|
||
|
};
|
||
|
}
|
||
|
|
||
|
export { hslaToRgba };
|