I have a color picker in my application that users can use to pick colors of certain objects that the application outputs. The color picker is outputting the color chosen in RGBA format. However, I need the HTML color code. I need to be able to convert RGBA, without knowing the color ahead of time, to HTML and use it as a string later. How would I go about doing this?
The rgba() functional notation expresses a color according to its red, green, and blue components.
Converting RGBA to hex with the #rgba or #rrggbbaa notation follows virtually the same process as the opaque counterpart. Since the alpha ( a ) is normally a value between 0 and 1, we need to multiply it by 255, round the result, then convert it to hexadecimal.
To get the RGBa code, just double click the foreground color and a window with color information will pop up. Then copy the RGBa value to your clipboard.
RGB Value. Each parameter (red, green, and blue) defines the intensity of the color between 0 and 255. For example, rgb(255, 0, 0) is displayed as red, because red is set to its highest value (255) and the others are set to 0. To display black, set all color parameters to 0, like this: rgb(0, 0, 0).
RGBA is natively supported by CSS3:
div {
background: rgba(200, 54, 54, 0.5);
}
Firefox, Safari, Chrome, IE9 and Opera browsers all support RGBA. Older IE's do not support it.
Fortunately, you can specify RGBA colours for browsers that support it and an alternative for browsers that do not. Check this link for a great howto.
These are the two options: - from the link -
1. FALLING BACK TO SOLID COLOUR: Allow the browser to fall back to using a solid colour when opacity isn’t available. The
h1 {
color: rgb(127, 127, 127);
color: rgba(0, 0, 0, 0.5); //for modern browsers only
}
2. FALLING BACK TO A PNG: In cases where you’re using transparency on a background-color (although not on borders or text) it’s possible to fall back to using a PNG with alpha channel to get the same effect. This is less flexible than using CSS as you’ll need to create a new PNG for each level of transparency required, but it can be a useful solution.
h1 {
background: transparent url(imageName.png);
background: rgba(0, 0, 0, 0.5) none; //for modern browsers only
}
What I am trying to say is that you do not need the HTML color code, you just need to add the css property rgba
- with javascript or jquery - after you pick up the color and I think you are done.
Hope it helps.
If you're looking for an actual conversion (which the text of your question literally asks for) from rgb(a) to hex in JavaScript:
red = green = blue = 255;
hex = '#' +
("0" + (red).toString(16)).slice(-2) +
("0" + (green).toString(16)).slice(-2) +
("0" + (blue).toString(16)).slice(-2);
There is of course no alpha equivalent, but you could set the opacity (and/or browser specific -opacity
values for older browser support).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With