Skip to content

Instantly share code, notes, and snippets.

@leocaseiro
Last active November 6, 2016 10:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save leocaseiro/87b9f084acd087f62152b501e2670404 to your computer and use it in GitHub Desktop.
Save leocaseiro/87b9f084acd087f62152b501e2670404 to your computer and use it in GitHub Desktop.
Javascript parse colours (Hex to RGB and vice versa) as well as luminance(dark or bright)
/**
* Original code from https://github.com/mike-schultz/materialette
*/
function rgbToHex(r, g, b) {
return "#" + ((1 << 24) + (parseInt(r) << 16) + (parseInt(g) << 8) + parseInt(b)).toString(16).slice(1);
}
function hexToRgb(hex) {
const 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;
}
/**
* luminance(hex, '#fff', '#000')
*/
function luminance(sHexColor, sLight, sDark) {
const oRGB = hexToRgb(sHexColor);
const yiq = ((oRGB.r * 299) + (oRGB.g * 587) + (oRGB.b * 114)) / 1000;
return (yiq >= 128) ? sDark : sLight;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment