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.
Practical examples
RGB color components can be presented in two ranges:
- from
0to1 - from
0to255
In the below sections you can find examples for the both.
RGB (components from 0 to 1)
// ONLINE-RUNNER:browser;
const toString = (component) => {
if (component < 0 || component > 1) {
throw new Error('Incorrect color component value.');
}
const value = Math.round(255 * component);
const text = value.toString(16);
if (text.length < 2) {
return '0' + text;
}
return text;
};
const toHex = (rgb) => '#' + toString(rgb.red) + toString(rgb.green) + toString(rgb.blue);
// Usage example:
const rgb = {red: 1, green: 1, blue: 0};
const hex = toHex(rgb);
console.log(hex);
RGB (components from 0 to 255)
// ONLINE-RUNNER:browser;
const toString = (component) => {
if (component < 0 || component > 255) {
throw new Error('Incorrect color component value.');
}
const text = component.toString(16);
if (component < 16) {
return '0' + text;
}
return text;
};
const toHex = (rgb) => '#' + toString(rgb.red) + toString(rgb.green) + toString(rgb.blue);
// Usage example:
const rgb = {red: 255, green: 255, blue: 0};
const hex = toHex(rgb);
console.log(hex);