Reputation: 483
I have a color in decimal form and need to transform it into rgb and back to de, so I used this to do so:
var currentcolor = 0xffd100;
const rgb_format = (c) => {
var newrgb = {r: (c & 0xff0000) >> 16,
g: (c & 0x00ff00) >> 8,
b: (c & 0x0000ff)}
return newrgb;
};
var rgb = rgb_format(currentcolor);
const decimal_format = (newrgb) => {
let decimal = (newrgb.r << 16) + (newrgb.g << 8) + (newrgb.b);
console.log(decimal);
return decimal;
};
color.color = decimal_format(rgb);
Thing is, I have a rgb editor with sliders for each value(r, g, b). And they work as they should, but when the value is 16 or less in r
the other sliders(g, b) stop changing the color of the component I am editing the color of.
Same happens when r
and b
are 0 and g
is greater than 16. In this case, g changes the color to red while it is less than 16, and when it's greater than 16 it doesn't display color.
Here is a gif to show my problem:
color-editing-problem-gif
or
alternate
Upvotes: 1
Views: 337
Reputation: 1074266
...I am also displaying the color like this:
style="background: #{currentcolor.toString(16)};
That won't work correctly. Consider the color 1092 decimal (0x000444). If currentcolor
has that value, currentcolor.toString(16)
results in 444
. #444
is not the same as #000444
in CSS, #444
is the color #444444
. Similarly, the color 65535 (0x00FFFF) will result in #ffff
, which is an invalid CSS color (they must be three or six digits, not four).
To output the color correctly, you need to pad the start of the string:
style="background: #{currentcolor.toString(16).padStart(6, "0")}
Upvotes: 1