Languages
[Edit]
EN

JavaScript - convert RGB color to CSS HEX color

8 points
Created by:
Majid-Hajibaba
972

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 0 to 1
  • from 0 to 255

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);

 

See also

  1. JavaScript - convert RGB color to 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