Last active
September 11, 2019 07:56
-
-
Save lqez/901a8488e9a71c810671e162cb1bc109 to your computer and use it in GitHub Desktop.
get proper text color for given background color (even with true-background color for transparency background)
This file contains hidden or 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
export function properTextColor(backColor, trueBackColor) { | |
function getRGBAfromHEX(color) { | |
color = color.slice(1).replace(color.length < 5 && /./g, '$&$&'); | |
color = parseInt(color.length > 6 ? color : color + 'FF', 16); | |
return { | |
r: color >>> 24, | |
g: color >>> 16 & 255, | |
b: color >>> 8 & 255, | |
a: color & 255 | |
}; | |
} | |
function getHSPfromRGB(r, g, b) { | |
return Math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b)); | |
} | |
let c = getRGBAfromHEX(backColor); | |
let b = getRGBAfromHEX(trueBackColor || '#FFFFFF'); | |
Array.from('rgb').forEach(_ => {c[_] = (c[_] * c.a + b[_] * (255 - c.a)) / 255}); | |
return (getHSPfromRGB(c.r, c.g, c.b) > 160) ? '#000000' : '#FFFFFF'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment