-
-
Save kartiknair/df6b9e2937f98f7d8b32e477b9989b22 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { cloudflareColors } from "./colors"; | |
const hexToRgb = (hexString) => { | |
if (hexString.startsWith("#")) hexString = hexString.substr(1); | |
return [ | |
parseInt(hexString.substring(0, 2), 16), | |
parseInt(hexString.substring(2, 4), 16), | |
parseInt(hexString.substring(4, 6), 16), | |
]; | |
}; | |
const relativeLuminance = (rgbArray) => { | |
let [r, g, b] = rgbArray.map((channel) => { | |
return channel / 255 <= 0.03928 | |
? channel / 255 / 12.92 | |
: ((channel / 255 + 0.055) / 1.055) ** 2.4; | |
}); | |
return 0.2126 * r + 0.7152 * g + 0.0722 * b; | |
}; | |
const getContrast = (color1, color2) => { | |
const luminance1 = relativeLuminance(hexToRgb(color1)), | |
luminance2 = relativeLuminance(hexToRgb(color2)); | |
return luminance1 > luminance2 | |
? (luminance1 + 0.05) / (luminance2 + 0.05) | |
: (luminance2 + 0.05) / (luminance1 + 0.05); | |
}; | |
let accessibleCombo = null; | |
while (!accessibleCombo) { | |
let randomPair = [ | |
cloudflareColors[Math.floor(Math.random() * cloudflareColors.length)].hex, | |
cloudflareColors[Math.floor(Math.random() * cloudflareColors.length)].hex, | |
]; | |
if (getContrast(randomPair[0], randomPair[1]) > 7.1) | |
accessibleCombo = randomPair; | |
} | |
const newStyle = document.createElement("style"); | |
newStyle.innerHTML = ` | |
main { | |
background-color: ${accessibleCombo[0]}; | |
color: ${accessibleCombo[1]}; | |
} | |
`; | |
document.head.appendChild(newStyle); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment