diff --git a/snippets/HSLToRGB.md b/snippets/HSLToRGB.md new file mode 100644 index 000000000..2c764128e --- /dev/null +++ b/snippets/HSLToRGB.md @@ -0,0 +1,26 @@ +--- +title: HSLToRGB +tags: math,intermediate +--- + +Converts a HSL color tuple to RGB format. + +- Use the [HSL to RGB conversion formula](https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_RGB) to convert to the appropriate format. +- The range of the input parameters is H: [0, 360], S: [0, 100], L: [0, 100]. +- The range of all output values is [0, 255]. + +```js +const HSLToRGB = (h, s, l) => { + s /= 100; + l /= 100; + const k = n => (n + h / 30) % 12; + const a = s * Math.min(l, 1 - l); + const f = n => + l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1))); + return [255 * f(0), 255 * f(8), 255 * f(4)]; +}; +``` + +```js +HSLToRGB(13, 100, 11); // [56.1, 12.155, 0] +``` diff --git a/snippets/RGBToHSL.md b/snippets/RGBToHSL.md new file mode 100644 index 000000000..1d7ddb2a1 --- /dev/null +++ b/snippets/RGBToHSL.md @@ -0,0 +1,36 @@ +--- +title: RGBToHSL +tags: math,intermediate +--- + +Converts a RGB color tuple to HSL format. + +- Use the [RGB to HSL conversion formula](https://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl/) to convert to the appropriate format. +- The range of all input parameters is [0, 255]. +- The range of the resulting values is H: [0, 360], S: [0, 100], L: [0, 100]. + +```js +const RGBToHSL = (r, g, b) => { + r /= 255; + g /= 255; + b /= 255; + const l = Math.max(r, g, b); + const s = l - Math.min(r, g, b); + const h = s + ? l === r + ? (g - b) / s + : l === g + ? 2 + (b - r) / s + : 4 + (r - g) / s + : 0; + return [ + 60 * h < 0 ? 60 * h + 360 : 60 * h, + 100 * (s ? (l <= 0.5 ? s / (2 * l - s) : s / (2 - (2 * l - s))) : 0), + (100 * (2 * l - s)) / 2, + ]; +}; +``` + +```js +RGBToHSL(45, 23, 11); // [21.17647, 60.71428, 10.98039] +```