Skip to content

Instantly share code, notes, and snippets.

@otnansirk
Last active June 5, 2023 23:38
Show Gist options
  • Save otnansirk/a89156bff71ce02ae028a8b3ff6be102 to your computer and use it in GitHub Desktop.
Save otnansirk/a89156bff71ce02ae028a8b3ff6be102 to your computer and use it in GitHub Desktop.
How to detect color included in the dark or light category
function isDarkColor(color) {
const luminance = (0.299 * color[0] + 0.587 * color[1] + 0.114 * color[2]) / 255;
return luminance <= 0.5;
}
function hexToRgb(hex) {
const r = parseInt(hex.substring(1, 3), 16);
const g = parseInt(hex.substring(3, 5), 16);
const b = parseInt(hex.substring(5, 7), 16);
return [r, g, b];
}
const colorHex = "#c9baba"; // hexa color
const colorRgb = hexToRgb(colorHex); // convert to RGB
if (isDarkColor(colorRgb)) {
console.log("Color is dark category");
} else {
console.log("Color is light category");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment