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?
2 Answers
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.
4 Comments
"#ff0000" 2. an RGBA value - like "rgb(255,0,0, 0.5)" 3. a color name - like "red"transparent or none component inside background property value since its overrided (if browser supports entire value) entirely anyway. It should be enough to write just background: url(imageName.png); background: rgba(0, 0, 0, 0.5);.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).
canvascontext has aglobalAlphaproperty which you can use for setting up the transparency of the canvas object.