Search code examples
javascripthexrgbrgba

Receive incorrect alpha channel when convert rgba color to hex


In order to convert rgba color with alpha channel to hex I use the code

let rChannel = 255;
let gChannel = 255;
let bChannel = 255;
let aChannel = 0.7;

console.log('#'+(256 + parseFloat(rChannel)).toString(16).substr(1) + ((1 << 24) + (parseFloat(gChannel) << 16) | (parseFloat(bChannel) << 8) | aChannel).toString(16).substr(1));
// #ffffff00, but expect #ffffffb3

It's given from the answer by the link https://stackoverflow.com/a/9766195/3208225

But it returns incorrect alpha channel in hex (00 instead of b3).

How to fix?


Solution

  • Using a bitwise | (or) operator on a floating-point value does not make sense. You'll have to use ~~(achannel * 255) to get an integer value.

    Depending on the range of your 0 ... 1 achannel values, you might want to use 256 instead of 255 if the value can never be 1.

    edit — now that I think about it, you don't need the ~~ explicit integer conversion, because the | will do that anyway, so simply (achannel * 256) will work so long as the fractional value will always be less than 1; otherwise 255.