Skip to content

Instantly share code, notes, and snippets.

@BenOsodrac BenOsodrac/getContrast
Last active Apr 14, 2019

Embed
What would you like to do?
getContrast color function
var getContrast = function(background, foreground) {
// Convert hex to rgb
var backgroundRGB = 'rgb(' + (background = background.replace('#', '')).match(new RegExp('(.{' + background.length/3 + '})', 'g')).map(function(l) { return parseInt(background.length%2 ? l+l : l, 16); }).join(',') + ')';
var foregroundRGB = 'rgb(' + (foreground = foreground.replace('#', '')).match(new RegExp('(.{' + foreground.length/3 + '})', 'g')).map(function(l) { return parseInt(foreground.length%2 ? l+l : l, 16); }).join(',') + ')';
// Get array of RGB values
var backgroundRGBArray = backgroundRGB.replace(/[^\d,]/g, '').split(',');
var foregroundRGBArray = foregroundRGB.replace(/[^\d,]/g, '').split(',');
function luminance(r, g, b) {
var a = [r, g, b].map(function (v) {
v /= 255;
return v <= 0.03928 ? v / 12.92 : Math.pow( (v + 0.055) / 1.055, 2.4 );
});
return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722;
}
function floor(number, decimals) {
decimals = +decimals || 0;
var multiplier = Math.pow(10, decimals);
return Math.floor(number * multiplier) / multiplier;
}
function contrast(el1, el2) {
l1 = (luminance(el1[0], el1[1], el1[2]) + 0.05);
l2 =(luminance(el2[0], el2[1], el2[2]) + 0.05);
ratio = l1/l2;
if (l2 > l1) {
ratio = 1 / ratio;
}
return floor(ratio, 2);
}
var contrast = contrast(backgroundRGBArray, foregroundRGBArray);
return contrast;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.