Languages
[Edit]
EN

JavaScript - convert RGB color to HEX color

6 points
Created by:
Wallace
636

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 toString = (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) => toString(r) + toString(g) + toString(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

 

See also

  1. JavaScript - convert RGB color to CSS HEX color

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