Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Hex to RGBA

My fiddle - http://jsbin.com/pitu/1/edit

I wanted to try an easy hex to rgba conversion. Ever browser I've used renders colors using rgb as default so when using the farbtastic color picker I'm converting the hex value to rgb by grabbing the background color the hex value generates (as rgb by default = simple conversion)

I tried replacing the ) symbol to , 1), but that didn't work so I went to just see how converting rgb to rgba would work, and I'm still having trouble.

The jquery

$('.torgb').val($('#color').css('background-color')); $('.torgba').val().replace(/rgb/g,"rgba"); 

The goal
enter image description here

EDIT:

TinyColor Is a great color manipulation js library that does everything I want here and more. I figure you guys may want to give it a try! - https://github.com/bgrins/TinyColor

like image 454
Michael Schwartz Avatar asked Feb 08 '14 13:02

Michael Schwartz


People also ask

Can I use hex in RGBA?

In CSS, there are several formats for colors that can be used. Common ones include hex (hexadecimal) codes, RGB (red, green, blue), RGBA (red, green, blue, alpha), and HSL (hue, saturation, lightness).

How do you find the RGBA of a color?

Choose the Eyedropper tool. Click somewhere on an open design, hold down and drag, and then you can actually sample color from anywhere on your screen. To get the RGBa code, just double click the foreground color and a window with color information will pop up. Then copy the RGBa value to your clipboard.

Is RGBA the same as hex?

RGB, RGBA, and HEX are the different types to display colors in CSS. Whereas RGB is a combination of three colors (Red, Green, and Blue), RGBA is the same as RGB with the extension of alpha (alpha=transperancy) and HEX uses the hexadecimal values to represent colors.


2 Answers

//If you write your own code, remember hex color shortcuts (eg., #fff, #000)  function hexToRgbA(hex){     var c;     if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){         c= hex.substring(1).split('');         if(c.length== 3){             c= [c[0], c[0], c[1], c[1], c[2], c[2]];         }         c= '0x'+c.join('');         return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+',1)';     }     throw new Error('Bad Hex'); }  hexToRgbA('#fbafff')  /*  returned value: (String) rgba(251,175,255,1) */ 
like image 96
kennebec Avatar answered Sep 30 '22 21:09

kennebec


@ElDoRado1239 has the right idea, but there's also a cleaner way:

function hexToRGB(hex, alpha) {      var r = parseInt(hex.slice(1, 3), 16),          g = parseInt(hex.slice(3, 5), 16),          b = parseInt(hex.slice(5, 7), 16);        if (alpha) {          return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")";      } else {          return "rgb(" + r + ", " + g + ", " + b + ")";      }  }    hexToRGB('#FF0000', 0.5);
like image 30
AJFarkas Avatar answered Sep 30 '22 21:09

AJFarkas