@akashshyam/color-utilities
Version:
A handy, tiny utility library compatible with typescript. We offer color conversions, color validation, constrast comparison etc
40 lines (39 loc) • 1.51 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getContrast = void 0;
var colorConversion_1 = require("./colorConversion");
var colorSeparation_1 = require("./colorSeparation");
/**
* Calculates the contrast against black or white
* @param color a color string of one of the supported formats(hex, rgb and hsl)
* @param colorFormat the format in which the color is provided(hex, rgb or hsl)
* @returns either 'black' or 'white' after calculating the contrast
*/
function getContrast(color, colorFormat) {
var _a, _b;
if (colorFormat === void 0) { colorFormat = 'hex'; }
var r = 0, b = 0, g = 0;
// Convert to RGB value
switch (colorFormat) {
case 'hex':
_a = colorConversion_1.hexToRGB(color, true), r = _a[0], g = _a[1], b = _a[2];
break;
case 'rgb':
var rgb = color.replace(/[^\d,]/g, '').split(',');
r = parseInt(rgb[0]);
g = parseInt(rgb[0]);
b = parseInt(rgb[0]);
break;
case 'hsl':
var _c = colorSeparation_1.separateHSL(color), h = _c[0], s = _c[1], l = _c[2];
_b = colorConversion_1.HSLToRGB(parseInt(h), parseInt(s), parseInt(l), true), r = _b[0], g = _b[1], b = _b[2];
break;
default:
break;
}
// Get YIQ ratio
var yiq = (r * 299 + g * 587 + b * 114) / 1000;
// Check contrast
return yiq >= 128 ? 'black' : 'white';
}
exports.getContrast = getContrast;