Chanwoo Park
Chanwoo Park

Reputation: 246

convert rgba color value to 0xFFFFFFFF form in javascript

For example, converting rgba(0,0,0,1) would be 4278190080 (result of 0xFF000000).

Upvotes: 0

Views: 2724

Answers (3)

Pranoy Sarkar
Pranoy Sarkar

Reputation: 2233

    function rgba(red,green,blue,trans){
        let hex='#';
        red=Number(red).toString(16);
        if(red.length<2){ // if one digit need to append 0 infront 
            hex+='0'+red; 
        }
        else{
            hex+=red;
        }

        green=Number(green).toString(16);
        if(green.length<2){
            hex+='0'+green;
        }
        else{
            hex+=green;
        }

        blue=Number(blue).toString(16);
        if(blue.length<2){
            hex+='0'+blue;
        }
        else{
            hex+=blue;
        }

        trans=Number(trans*255).toString(16);
        trans=trans.replace(/\..*/,'');
        if(red.length<2){
            hex+='0'+trans;
        }
        else{
            hex+=trans;
        }
        return hex;
    }

console.log(rgba(0,0,0,1));//#0000000ff
console.log(rgba(255,255,255,.5))//#ffffff7f
console.log(rgba(151,12,55,.89))//#970c37e2

RBGA takes red , green blue and transparency

all RGB is range from 0 to 255 but transparencey is 0 to 1 check here in mdn for that we need to take special care , simply 1 translates to 255

I tested on chrome its working as expected

Upvotes: 0

Chanwoo Park
Chanwoo Park

Reputation: 246

I asked this question because given color for example, convertin color #4286F4 to 0xFF4286F4 would not render the same color.

Silly for me I thought 0xFFFFFFFF is formed in order of Alpha(opacity),Red,Green,Blue. But I found out that its order represents Alpha,Blue,Green,Red. so converting #4286F4 to the given format would be 0xFFF48642.

Upvotes: 0

Ricky Mo
Ricky Mo

Reputation: 7618

Simply shift then or. You can also use multiply then add if you want.

var r = 80;
var g = 130;
var b = 211;
var hex = 0xff000000 | ( r << 16) | ( g << 8) | b;
console.log((hex >>> 0).toString(16));

Upvotes: 3

Related Questions