Created
January 19, 2021 11:23
-
-
Save Youenn-Bouglouan/a1d93777aa84ca9b1f151cff27adec5b to your computer and use it in GitHub Desktop.
Convert HSL to RGB colors - helpers - javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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