Is it possible to convert a colour as such #ff0000
to rgb?
So convert #ff0000
to rgb(255,0,0);
I'm pretty sure this has got to be possible, I just don't know how. Any insight would be great!
Is it possible to convert a colour as such #ff0000
to rgb?
So convert #ff0000
to rgb(255,0,0);
I'm pretty sure this has got to be possible, I just don't know how. Any insight would be great!
You could use:
var s = "#ff0000";
var patt = /^#([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})$/;
var matches = patt.exec(s);
var rgb = "rgb("+parseInt(matches[1], 16)+","+parseInt(matches[2], 16)+","+parseInt(matches[3], 16)+");";
alert(rgb);
.css("background-color")
will return rgb http://api.jquery.com/css/
here is the fiddle http://jsfiddle.net/3nigma/msRqv/1/
What about this algorithm?
http://www.javascripter.net/faq/hextorgb.htm
You could even create a JQuery plugin that uses that algorithm. I think it would be cool. I don't know if there exists one already.
Purely working with the string you have, you could something like this :
var color = '#FF5500';
First, extract the two hexadecimal digits for each color :
var redHex = color.substring(1, 3);
var greenHex = color.substring(3, 5);
var blueHex = color.substring(5, 7);
Then, convert them to decimal :
var redDec = parseInt(redHex, 16);
var greenDec = parseInt(greenHex, 16);
var blueDec = parseInt(blueHex, 16);
And, finally, get your rgb()
string as a result :
var colorRgb = 'rgb(' + redDec + ', ' + greenDec + ', ' + blueDec + ')';
console.log( colorRgb );
And you get as output :
rgb(255, 85, 0)
You have to separate all three components from the Hex definition, then convert them to decimal. This works:
function hex2rgba(x,a) {
var r=x.replace('#','').match(/../g),g=[],i;
for(i in r){g.push(parseInt(r[i],16));}g.push(a);
return 'rgba('+g.join()+')';
}
Try this:
http://jsfiddle.net/AlienWebguy/AfVhs/1/