Wednesday, 25 August 2010

Converting between rgb and hex colors in javascript

Recently I've need to be able to convert between rgb and hex colors.

Here's the javascript functions I used.

function hex2Rgba(hexColor, opacity) {
// Only accepts #123456 format for now
if (color[0] === '#' && color.length === 7) {

var r,g,b;
r = parseInt(color.substring(1,3), 16);
g = parseInt(color.substring(3,5), 16);
b = parseInt(color.substring(5,7), 16);

//
return "rgba("+r+","+g+","+b+","+opacity+")";
}
return null;
}

Obviously this is pretty basic, and doesn't support the #123 format.

For converting in the other direction I found this code on stackoverflow..

function rgb2hex(rgb) {
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

No comments:

Post a Comment