Skip to content

Instantly share code, notes, and snippets.

@joekrump
Created February 2, 2022 05:31
Show Gist options
  • Save joekrump/48d199f0eec28935914767b7c587a1b2 to your computer and use it in GitHub Desktop.
Save joekrump/48d199f0eec28935914767b7c587a1b2 to your computer and use it in GitHub Desktop.
Color helpers
/**
* @param {string} hexString
* @returns {{ r: number; g: number; b: number; }}
*/
function getRGBFromHex(hexString) {
hexString = hexString.substring(1);
let aRgbHex = hexString.match(/.{1,2}/g);
return {
r: parseInt(aRgbHex[0], 16),
g: parseInt(aRgbHex[1], 16),
b: parseInt(aRgbHex[2], 16),
};
}
/**
* @param {{r: number; g: number; b: number;}} param0
* @returns {'#ffffff' | '#000000';}
*/
function getContrastingColorBasedOnLuminosity({ r, g, b }) {
return r * 0.299 + g * 0.587 + b * 0.114 > 186 ? "#000000" : "#ffffff";
}
export { getRGBFromHex, getContrastingColorBasedOnLuminosity };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment