From a413143ea13edc475cd242d1675e26c76329e849 Mon Sep 17 00:00:00 2001 From: Soham Pal Date: Fri, 18 Sep 2020 16:55:07 +0530 Subject: [PATCH] Added a snippets to convert RGB colour format into HSV and vice versa. (#1213) Co-authored-by: Angelos Chalaris --- snippets/HSBToRGB.md | 24 ++++++++++++++++++++++++ snippets/RGBToHSB.md | 27 +++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 snippets/HSBToRGB.md create mode 100644 snippets/RGBToHSB.md diff --git a/snippets/HSBToRGB.md b/snippets/HSBToRGB.md new file mode 100644 index 000000000..1926a5333 --- /dev/null +++ b/snippets/HSBToRGB.md @@ -0,0 +1,24 @@ +--- +title: HSBToRGB +tags: math,intermediate +--- + +Converts a HSB color tuple to RGB format. + +- Use the [HSB to RGB conversion formula](https://en.wikipedia.org/wiki/HSL_and_HSV#HSV_to_RGB) to convert to the appropriate format. +- The range of the input parameters is H: [0, 360], S: [0, 100], B: [0, 100]. +- The range of all output values is [0, 255]. + +```js +const HSBToRGB = (h, s, b) => { + s /= 100; + b /= 100; + const k = (n) => (n + h / 60) % 6; + const f = (n) => b * (1 - s * Math.max(0, Math.min(k(n), 4 - k(n), 1))); + return [255 * f(5), 255 * f(3), 255 * f(1)]; +}; +``` + +```js +HSBToRGB(18, 81, 99); // [252.45, 109.31084999999996, 47.965499999999984] +``` diff --git a/snippets/RGBToHSB.md b/snippets/RGBToHSB.md new file mode 100644 index 000000000..38410de0a --- /dev/null +++ b/snippets/RGBToHSB.md @@ -0,0 +1,27 @@ +--- +title: RGBToHSB +tags: math,intermediate +--- + +Converts a RGB color tuple to HSB format. + +- Use the [RGB to HSB conversion formula](https://en.wikipedia.org/wiki/HSL_and_HSV#From_RGB) 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], B: [0, 100]. + +```js +const RGBToHSB = (r, g, b) => { + r /= 255; + g /= 255; + b /= 255; + const v = Math.max(r, g, b), + n = v - Math.min(r, g, b); + const h = + n && v === r ? (g - b) / n : v === g ? 2 + (b - r) / n : 4 + (r - g) / n; + return [60 * (h < 0 ? h + 6 : h), v && (n / v) * 100, v * 100]; +}; +``` + +```js +RGBToHSB(252, 111, 48); // [18.529411764705856, 80.95238095238095, 98.82352941176471] +```