Languages
[Edit]
EN

JavaScript - convert HSV color to RGB color

7 points
Created by:
Ela-Davey
663

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

 

References

  1. HSV to RGB - Wikipedia
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join