JavaScript library used to convert a hexadecimal color to RGB and find the appropriate text color (white or black) given a background color
var Color = function () {};
/**
* Figures out if a string is a hexadecimal or
* string rendering of RGB (rgb(...)) and converts
* it to an RGB object that we can parse
* @param {string} string
*/
Color.prototype.stringToRGB = function (string) {
// if rgb
var rgbTest = /rgb\(/;
if (rgbTest.test(string)) {
return this.rgbStingToRGB(string);
}
// if hex
var hexTest = /(#?([A-Fa-f0-9]){3}(([A-Fa-f0-9]){3})?)/;
if (hexTest.test(string)) {
return this.hexToRGB(string);
}
return null;
};
/**
* Convert a hexadecimal color to RGB.
* From: http://stackoverflow.com/a/5624139/2662151
* @param {string} hex Hexadecimal color
*/
Color.prototype.hexToRGB = function (hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
};
Color.prototype.rgbStingToRGB = function (string) {
var parts = string.replace("rgb(", "").replace(")", "").replace(" ", "").split(",");
return {
r: parts[0],
g: parts[1],
b: parts[2]
};
};
Color.prototype.hex = function (x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
};
Color.prototype.rgb2hex = function (string) {
if (/^#[0-9A-F]{6}$/i.test(string)) return string;
string = string.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
return this.hex(string[1]) + this.hex(string[2]) + this.hex(string[3]);
};
/**
* Return white if given a dark color.
* Return black if given a light color.
*/
Color.prototype.getContrastingColor = function (r, g, b) {
if (!g && !b) {
var rgb = this.stringToRGB(r);
if (!rgb) return null;
r = rgb.r;
g = rgb.g;
b = rgb.b;
}
// W3C algorithm
var o = Math.round(((parseInt(r) * 299) + (parseInt(g) * 587) + (parseInt(b) * 114)) / 1000);
return o > 125 ? "000" : "fff";
};
module.exports = new Color();