Skip to content

Instantly share code, notes, and snippets.

@dcondrey
Created October 28, 2015 20:44
Show Gist options
  • Save dcondrey/183971f17808e9277572 to your computer and use it in GitHub Desktop.
Save dcondrey/183971f17808e9277572 to your computer and use it in GitHub Desktop.
/**
* Calculate the contrast of a color to determine the appropriate opposing text color.
* @author D. Condrey
* @param {string|object} - element background-color or element
* @return {string}
* white - if background is a dark shade color
* black - if background is a light shade color
*/
define(function() {
'use strict';
var colors = {};
colors.contrast = function(rgb) {
// check if we are receiving an element or element background-color
if (rgb instanceof jQuery) {
// get element background-color
rgb = rgb.css('background-color');
} else if (typeof rgb !== 'string') {
return;
}
// @TODO check for HEX value
// All browsers should return an rgb value so this isn't critical
// Strip everything except the integers eg. "rgb(" and ")" and " "
rgb = rgb.split(/\(([^)]+)\)/)[1].replace(/ /g, '');
// map RGB values to variables
var r = parseInt(rgb.split(',')[0], 10),
g = parseInt(rgb.split(',')[1], 10),
b = parseInt(rgb.split(',')[2], 10),
a;
// if RGBA, map alpha to variable (not currently in use)
if (rgb.split(',')[3] !== null) {
a = parseInt(rgb.split(',')[3], 10);
}
// calculate contrast of color (standard grayscale algorithmic formula)
var contrast = (Math.round(r * 299) + Math.round(g * 587) + Math.round(b * 114)) / 1000;
return (contrast >= 128) ? 'black' : 'white';
};
// Return public interface
return colors;
});
@chmurson
Copy link

chmurson commented Feb 5, 2021

nice!

@NerdyDeedsLLC
Copy link

NerdyDeedsLLC commented Jun 29, 2023

...could do. Could do.

Or... yanno...

function contrastingColor(hex, factorAlpha=false) {
    let [r,g,b,a]=hex.replace(/^#?(?:(?:(..)(..)(..)(..)?)|(?:(.)(.)(.)(.)?))$/, '$1$5$5$2$6$6$3$7$7$4$8$8').match(/(..)/g).map(rgb=>parseInt('0x'+rgb));
    return ((~~(r*299) + ~~(g*587) + ~~(b*114))/1000) >= 128 || (!!(~(128/a) + 1) && factorAlpha) ? '#000' : '#FFF';   
}

...which takes any form of HEX or HEXA color code (#RGB/#RGBA/#RRGGBB/#RRGGBBAA; "#" is optional), along with a second param telling it if it should factor opacity.

Returns #FFF or #000.

image

It's a utility function!

@chmurson
Copy link

@NerdyDeedsLLC looks like some kind of Trojan horse kind of snippet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment