EN
JavaScript - convert HSV color to RGB color
7
points
In this short article, we would like to show how to convert HSV color to RGB color using JavaScript.
Practical example:
// ONLINE-RUNNER:browser;
// Converts HSV color to RGB.
// Arguments:
// hue from 0 to 360 degree
// saturation from 0 to 1
// value from 0 to 1
// Returns: RGB color (components from 0 to 1)
//
const toRgb = (hue, saturation, value) => {
let d = 0.0166666666666666 * hue;
let c = value * saturation;
let x = c - c * Math.abs(d % 2.0 - 1.0);
let m = value - c;
c += m;
x += m;
switch (d >>> 0) {
case 0: return {red: c, green: x, blue: m};
case 1: return {red: x, green: c, blue: m};
case 2: return {red: m, green: c, blue: x};
case 3: return {red: m, green: x, blue: c};
case 4: return {red: x, green: m, blue: c};
}
return {red: c, green: m, blue: x};
};
// Usage example:
const rgb = toRgb(200, 0.5, 0.5); // 200deg, 50%, 50%
console.log(`red: ${Math.round(255 * rgb.red )}`); // 64
console.log(`green: ${Math.round(255 * rgb.green)}`); // 106
console.log(`blue: ${Math.round(255 * rgb.blue )}`); // 128