Languages
[Edit]
EN

JavaScript - convert RGB color to HEX color

6 points
Created by:
Wallace
396

In this short article, we would like to show how to convert RGB color to HEX color using JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const toValue = (component) => {
    if (component > -1 && component < 256) {
      	const text = component.toString(16);
      	return text.length < 2 ? '0' + text : text;
    }
    throw new Error('Incorrect color component value.');
}

const toHex = (r, g, b) => {
	return '#' + toValue(r) + toValue(g) + toValue(b);
};


// Usage example:

//                  r    g    b        hex color
console.log(toHex(  0,   0,   0));  //  #000000
console.log(toHex(255, 255, 255));  //  #ffffff
console.log(toHex(255,   0,   0));  //  #ff0000
console.log(toHex(  0, 255,   0));  //  #00ff00
console.log(toHex(  0,   0, 255));  //  #0000ff

 

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