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 th
Here is a function that returns rgb or rgba if you provide an alpha. The function also converts short hex color codes too.
function:
function hexToRgb(hex, alpha) {
hex = hex.replace('#', '');
var r = parseInt(hex.length == 3 ? hex.slice(0, 1).repeat(2) : hex.slice(0, 2), 16);
var g = parseInt(hex.length == 3 ? hex.slice(1, 2).repeat(2) : hex.slice(2, 4), 16);
var b = parseInt(hex.length == 3 ? hex.slice(2, 3).repeat(2) : hex.slice(4, 6), 16);
if ( alpha ) {
return 'rgba(' + r + ', ' + g + ', ' + b + ', ' + alpha + ')';
}
else {
return 'rgb(' + r + ', ' + g + ', ' + b + ')';
}
}
examples:
hexToRgb('FF0000');// rgb(255, 0, 0)
hexToRgb('#FF0000');// rgb(255, 0, 0)
hexToRgb('#FF0000', 1);// rgba(255, 0, 0, 1)
hexToRgb('F00');// rgb(255, 0, 0)
hexToRgb('#F00');// rgb(255, 0, 0)
hexToRgb('#F00', 1);// rgba(255, 0, 0, 1)