EN
JavaScript - convert RGB color to CSS HEX color
8 points
In this short article, we would like to show how to convert RGB color to CSS HEX color using JavaScript.
RGB color components can be presented in two ranges:
- from
0
to1
- from
0
to255
In the below sections you can find examples for the both.
xxxxxxxxxx
1
const toString = (component) => {
2
if (component < 0 || component > 1) {
3
throw new Error('Incorrect color component value.');
4
}
5
const value = Math.round(255 * component);
6
const text = value.toString(16);
7
if (text.length < 2) {
8
return '0' + text;
9
}
10
return text;
11
};
12
13
const toHex = (rgb) => '#' + toString(rgb.red) + toString(rgb.green) + toString(rgb.blue);
14
15
16
// Usage example:
17
18
const rgb = {red: 1, green: 1, blue: 0};
19
const hex = toHex(rgb);
20
21
console.log(hex);
xxxxxxxxxx
1
const toString = (component) => {
2
if (component < 0 || component > 255) {
3
throw new Error('Incorrect color component value.');
4
}
5
const text = component.toString(16);
6
if (component < 16) {
7
return '0' + text;
8
}
9
return text;
10
};
11
12
const toHex = (rgb) => '#' + toString(rgb.red) + toString(rgb.green) + toString(rgb.blue);
13
14
15
// Usage example:
16
17
const rgb = {red: 255, green: 255, blue: 0};
18
const hex = toHex(rgb);
19
20
console.log(hex);