Skip to content

Instantly share code, notes, and snippets.

@Youenn-Bouglouan
Created January 19, 2021 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Youenn-Bouglouan/a1d93777aa84ca9b1f151cff27adec5b to your computer and use it in GitHub Desktop.
Save Youenn-Bouglouan/a1d93777aa84ca9b1f151cff27adec5b to your computer and use it in GitHub Desktop.
Convert HSL to RGB colors - helpers - javascript
const hueToRgb = (p, q, t) => {
let tlocal = t;
if (tlocal < 0) tlocal += 1;
if (tlocal > 1) tlocal -= 1;
if (tlocal < 1 / 6) return p + (q - p) * 6 * tlocal;
if (tlocal < 1 / 2) return q;
if (tlocal < 2 / 3) return p + (q - p) * (2 / 3 - tlocal) * 6;
return p;
};
/*
* Converts HSL values to RGB values.
* Expects the following input:
* - 'hue' within the [0, 360] range.
* - 'saturation' within the [0, 100] range.
* - 'lightness' within the [0, 100] range.
*/
export const hslToRgb = (hue, saturation, lightness) => {
if (saturation === 0) {
return {
red: lightness,
green: lightness,
blue: lightness,
};
}
const h = hue / 360;
const l = lightness / 100;
const s = saturation / 100;
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
return {
red: Math.round(hueToRgb(p, q, h + 1 / 3) * 255),
green: Math.round(hueToRgb(p, q, h) * 255),
blue: Math.round(hueToRgb(p, q, h - 1 / 3) * 255),
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment