EN
JavaScript - convert RGB color to HEX color
6
points
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