How to Convert HSB/HSV Color to RGB in JavaScript

The HSB/HSV representation describes colors with three values:

  1. H (Hue): It represents the type of color (0° to 360°).
  2. S (Saturation): It represents the variation from the primary color (0 to 1).
  3. B/V (Brightness/Value): It represents the brightness of the color (0 to 1).

The RGB representation, on the other hand, represents colors with three values:

  1. R (Red): The intensity of the red color (0 to 255).
  2. G (Green): The intensity of the green color (0 to 255).
  3. B (Blue): The intensity of the blue color (0 to 255).

To convert HSB/HSV color to RGB, you use the custom function:

function hsvToRgb(h, s, v) {
  let r, g, b;

  let i = Math.floor(h * 6);
  let f = h * 6 - i;
  let p = v * (1 - s);
  let q = v * (1 - f * s);
  let t = v * (1 - (1 - f) * s);

  switch (i % 6) {
    case 0: r = v, g = t, b = p; break;
    case 1: r = q, g = v, b = p; break;
    case 2: r = p, g = v, b = t; break;
    case 3: r = p, g = q, b = v; break;
    case 4: r = t, g = p, b = v; break;
    case 5: r = v, g = p, b = q; break;
  }

  return {
    r: Math.round(r * 255),
    g: Math.round(g * 255),
    b: Math.round(b * 255)
  };
}

let rgb = hsvToRgb(0.5, 0.5, 0.5);
console.log(rgb);

Output

{ r: 64, g: 128, b: 128 }

The function above assumes that the hue is normalized (i.e., between 0 and 1). If your hue is between 0 and 360, divide it by 360 before passing it to the function.