much better getTextColor function
This commit is contained in:
parent
d84c30480b
commit
fd8478df1e
1 changed files with 27 additions and 10 deletions
|
@ -1,4 +1,4 @@
|
||||||
import { invertLightness, contrastRatio } from 'chromatism'
|
import { invertLightness, contrastRatio, convert } from 'chromatism'
|
||||||
|
|
||||||
// useful for visualizing color when debugging
|
// useful for visualizing color when debugging
|
||||||
export const consoleColor = (color) => console.log('%c##########', 'background: ' + color + '; color: ' + color)
|
export const consoleColor = (color) => console.log('%c##########', 'background: ' + color + '; color: ' + color)
|
||||||
|
@ -187,19 +187,36 @@ export const rgba2css = function (rgba) {
|
||||||
* @param {Boolean} preserve - try to preserve intended text color's hue/saturation (i.e. no BW)
|
* @param {Boolean} preserve - try to preserve intended text color's hue/saturation (i.e. no BW)
|
||||||
*/
|
*/
|
||||||
export const getTextColor = function (bg, text, preserve) {
|
export const getTextColor = function (bg, text, preserve) {
|
||||||
const contrast = getContrastRatio(bg, text)
|
const originalContrast = getContrastRatio(bg, text)
|
||||||
|
if (!preserve) {
|
||||||
if (contrast < 4.5) {
|
if (originalContrast < 4.5) {
|
||||||
const base = typeof text.a !== 'undefined' ? { a: text.a } : {}
|
|
||||||
const result = Object.assign(base, invertLightness(text).rgb)
|
|
||||||
if (!preserve && getContrastRatio(bg, result) < 4.5) {
|
|
||||||
// B&W
|
// B&W
|
||||||
return contrastRatio(bg, text).rgb
|
return contrastRatio(bg, text).rgb
|
||||||
}
|
}
|
||||||
// Inverted color
|
|
||||||
return result
|
|
||||||
}
|
}
|
||||||
return text
|
|
||||||
|
const originalColor = convert(text).hex
|
||||||
|
const invertedColor = invertLightness(originalColor).hex
|
||||||
|
const invertedContrast = getContrastRatio(bg, invertedColor)
|
||||||
|
let workColor
|
||||||
|
|
||||||
|
if (invertedContrast > originalContrast) {
|
||||||
|
workColor = invertedColor
|
||||||
|
} else {
|
||||||
|
workColor = originalColor
|
||||||
|
}
|
||||||
|
|
||||||
|
let contrast = getContrastRatio(bg, text)
|
||||||
|
const result = convert(rgb2hex(workColor)).hsl
|
||||||
|
const delta = result.l > 50 ? 1 : -1
|
||||||
|
const multiplier = 10
|
||||||
|
while (contrast < 4.5) {
|
||||||
|
result.l += delta * multiplier
|
||||||
|
contrast = getContrastRatio(bg, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
const base = typeof text.a !== 'undefined' ? { a: text.a } : {}
|
||||||
|
return Object.assign(base, result)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
Loading…
Add table
Reference in a new issue