Question

I want to convert ARGB colors to CSS-compatible hex

for example:

-1 should be converted to #FFFFFF

or

-16777216 to #000000

How can I do that in JavaScript?

Was it helpful?

Solution

This discards any alpha component

function argbToRGB(color) {
    return '#'+ ('000000' + (color & 0xFFFFFF).toString(16)).slice(-6);
}

Your colors are signed 32-bits and full alpha (0xFF) makes the numbers negative. This code works even for unsigned numbers.

OTHER TIPS

I assume you want something like this:

function convertToColorString (argb){ 
   return '#'+ ('000000' + (argb+16777216).toString(16)).slice(-6); 
}

You may want to check this question: How do I convert an integer to a javascript color?

My reply to that question was roughly to suggest that, if you want to use a library rather than coding it yourself, the pusher.color Javascript library supports integer to HTML color conversions:

// Will set c to "#695083"
var c = pusher.color('packed_argb', -9875325).hex6();

Here's a JSFiddle if you want to try the above out.

Also, let me add the disclaimer that I wrote the library mentioned above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top