Sep 7, 2018 · 1 min read
It’s not the main point of the post, but there are better traditional approaches.
The 50% equation is broken [treating the hexcode as a number means saying 1 red = 256 green = 65536 blue].
The other method is reasonable, though it stems from analog signal processing in TVs — if brain.js is an option… its simplicity probably isn’t important.
Given that, if you want to give the traditional approach a fair shake, The web accessibility guidelines define the contrast ratio in a manner which implies the following approach:
const ungamma = (value) => {
const v = (value/255);
if(v<=0.03928) {
return v/12.92;
}
return Math.pow((v+0.055)/1.055,2.4)
}const getContrastWCAG = (r,g,b) => {
const luma = (ungamma(r)*0.2126 + ungamma(g)*0.7152 + ungamma(b)*0.0722);
const whiteContrast = 1.05/(luma+0.05);
const blackContrast = (luma+0.05)/0.05;
return (whiteContrast > blackContrast)? “white”:”black”; }
