I have to modify some code and the previous developer left this comment:
color: color, // e.g. '#RRGGBBFF' - Last 2 digits are alpha information
On the page there is a color picker that let's the user change text color. It gives HEX values like so:
And there is a slider that allows the user to change a text's transparency. It runs from
Somehow I need to get a 2 digit letter from this transparency amount and append it to the HEX value for it to work.
Does anyone know how to append Alpha information to HEX color codes? What is the math formula for it?
I guess the question can also be answered if anyone knows how to convert RGBA color values with transparency into HEX:
rgba(255, 255, 255, 0.6)
A two-digit hexadecimal number has a maximum value of
255 = (16 ** 2 - 1) and minimum of
0, your alpha has maximum
1 and minimum
0, so it's a simple matter of
// say we start with e.g. alpha = 0.3 x = alpha * 255; // float, e.g. x = 76.5
this won't always be an integer, so you'll most likely want to convert it to one, for example using
y = Math.floor(x); // int, e.g. y = 76
converting this into a base-16 string will give you your desired output
s = y.toString(16); // str, e.g. s = "4c"
y < 16 this will only be one digit, so you may need to pad an extra
ret = y < 16 ? '0' + s : s;
As always, use linear scaling.
(vald - mind) / (maxd - mind) * (maxr - minr) + minr
(0.1 - 0.0) / (1.0 - 0.0) * (255 - 0) + 0 = 25.5 ~= 0x1a
Per the relevant portion of the W3C spec, there is no hex version of RGBA values. Quoting from that spec:
Unlike RGB values, there is no hexadecimal notation for an RGBA value.
So, the work-around is that you use the
rgba(r, g, b, a) format or you set transparency separately.