Skip to content

Instantly share code, notes, and snippets.

@raduGaspar
Created March 31, 2017 13:50
Show Gist options
  • Save raduGaspar/dda3f81d4abff1a90e37ff7412493254 to your computer and use it in GitHub Desktop.
Save raduGaspar/dda3f81d4abff1a90e37ff7412493254 to your computer and use it in GitHub Desktop.
export default class PickerUtils {
/**
* Converts a hex color to RGB format
* @param {string} hex A hex color (shorthand allowed)
* @returns {object|null} Containing the RGB channels
*/
static hexToRGB(hex) {
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
const rgb = hex.replace(
shorthandRegex,
(m, r, g, b) => r + r + g + g + b + b
);
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(rgb);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
} : null;
}
/**
* Gets a contrasting dark or light background for any given hex color
* @param hex A hex color (shorthand allowed)
* @returns {string} A dark or light background
*/
static getContrast(hex) {
const color = PickerUtils.hexToRGB(hex);
// calculate perceptive luminance; human eye favors green color
const a = 1 - (0.299 * color.r + 0.587 * color.g + 0.114 * color.b) / 255;
return a < 0.5 ? 'dark' : 'light';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment