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:
xxxxxxxxxx
1
const toString = (component) => {
2
if (component > -1 && component < 256) {
3
const text = component.toString(16);
4
return text.length < 2 ? '0' + text : text;
5
}
6
throw new Error('Incorrect color component value.');
7
}
8
9
const toHex = (r, g, b) => toString(r) + toString(g) + toString(b);
10
11
12
// Usage example:
13
14
// r g b hex color
15
console.log(toHex( 0, 0, 0)); // 000000
16
console.log(toHex(255, 255, 255)); // ffffff
17
console.log(toHex(255, 0, 0)); // ff0000
18
console.log(toHex( 0, 255, 0)); // 00ff00
19
console.log(toHex( 0, 0, 255)); // 0000ff