技巧: 根据背景色自适应文本颜色

落日映苍穹つ 2022-12-27 12:40 223阅读 0赞

format_png

作者:wsafight

https://github.com/wsafight/personBlog/issues/27

针对企业服务来说,最终用户往往需要更加细化的信息分类方式,而打标签无疑是非常好的解决方案。

如果标签仅仅只提供几种颜色可能无法满足各个用户的实际需求。那么系统就需要为用户提供颜色选择。事实上我们完全无法预知用户选择了何种颜色,那么如果当前用户选择了黑色作为背景色,同时当前的字体颜色也是黑色,该标签就无法使用。如果配置背景色的同时还要求用户配置文字颜色,那么这个标签功能未免有些鸡肋。让用户觉得我们的开发水平有问题。

所以需要寻找一种解决方案来搞定这个问题。

问题解析

对于彩色转灰度,有一个著名的公式。我们可以把十六进制的代码分成3个部分,以获得单独的红色,绿色和蓝色的强度。用此算法逐个修改像素点的颜色可以将当前的彩色图片变为灰色图像。

  1. gray = r * 0.299 + g * 0.587 + b * 0.114

但是针对明亮和阴暗的颜色,经过公式的计算后一定会获得不同的数值,而针对当前不同值,我们取反就可以得到当前的文本颜色。即:

  1. const textColor = (r * 0.299 + g * 0.587 + b * 0.114) > 186 ? '#000' : '#FFF'

当然了,186 并不是一个确定的数值,你可以根据自己的需求调整一个新的数值。通过该算法,传入不同的背景色,就可以得到白色和黑色,或者自定义出比较合适的文本颜色。

完善代码

当然,虽然解决的方法非常简单,但是中间还是涉及了一些进制转换问题,这里简单传递数值如下所示。

  1. /**
  2. * @param backgroundColor 字符串 传入 #FFFBBC | FBC | FFBBCC 均可
  3. */
  4. export function contrastTextColor(backgroundHexColor: string) {
  5. let hex = backgroundHexColor
  6. // 如果当前传入的参数以 # 开头,去除当前的
  7. if (hex.startsWith('#')) {
  8. hex = hex.substring(1);
  9. }
  10. // 如果当前传入的是 3 位小数值,直接转换为 6 位进行处理
  11. if (hex.length === 3) {
  12. hex = [hex[0], hex[0], hex[1], hex[1], hex[2], hex[2]].join('')
  13. }
  14. if (hex.length !== 6) {
  15. throw new Error('Invalid background color.' + backgroundHexColor);
  16. }
  17. const r = parseInt(hex.slice(0, 2), 16)
  18. const g = parseInt(hex.slice(2, 4), 16)
  19. const b = parseInt(hex.slice(4, 6), 16)
  20. if ([r,g,b].some(x => Number.isNaN(x))) {
  21. throw new Error('Invalid background color.' + backgroundHexColor);
  22. }
  23. const textColor = (r * 0.299 + g * 0.587 + b * 0.114) > 186 ? '#000' : '#FFF'
  24. return textColor
  25. }

我们还可以在其中添加 rgb 颜色,以及转换逻辑。

  1. /**
  2. * @param backgroundColor 字符串
  3. */
  4. export function contrastTextColor(backgroundHexColor: string) {
  5. // 均转换为 hex 格式, 可以传入 rgb(222,33,44)。
  6. // 如果当前字符串参数长度大于 7 rgb(,,) 最少为 8 个字符,则认为当前传入的数值为 rgb,进行转换
  7. const backgroundHexColor = backgroundColor.length > 7 ? convertRGBToHex(backgroundColor) : backgroundColor
  8. // ... 后面代码
  9. }
  10. /** 获取背景色中的多个值,即 rgb(2,2,2) => [2,2,2] */
  11. const rgbRegex = /^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/
  12. /** 转换 10 进制为 16 进制,
  13. * 计算完成后时字符串前面加 0,同时取后两位数值。使得返回的数值一定是 两位数
  14. * 如 E => 0E | FF => 0FF => FF
  15. */
  16. const hex = (x: string) => ("0" + parseInt(x).toString(16)).slice(-2);
  17. function convertRGBToHex(rgb: string): string {
  18. const bg = rgb.match(rgbRegex);
  19. if (!bg) {
  20. // 返回空字符串,在后面判断长度为 6 时候会报错。不在此处进行操作
  21. return ''
  22. }
  23. return ("#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3])).toUpperCase();
  24. }

当然了,我们也可以在其中添加缓存代码,以便于减少计算量。

  1. // 使用 map 来缓存
  2. const colorByBgColor = new Map()
  3. // 缓存错误字符串
  4. const CACHE_ERROR = 'error'
  5. export function contrastTextColor(backgroundColor: string) {
  6. // 获取缓存
  7. const cacheColor = colorByBgColor.get(backgroundColor)
  8. if (cacheColor) {
  9. // 当前缓存错误,直接报错
  10. if (cacheColor === CACHE_ERROR) {
  11. throw new Error('Invalid background color.' + backgroundColor);
  12. }
  13. return colorByBgColor.get(backgroundColor)
  14. }
  15. // ...
  16. if (hex.length !== 6) {
  17. // 直接缓存错误
  18. colorByBgColor.set(backgroundColor, CACHE_ERROR)
  19. throw new Error('Invalid background color.' + backgroundColor);
  20. }
  21. // ...
  22. if ([r,g,b].some(x => Number.isNaN(x))) {
  23. // 直接缓存错误
  24. colorByBgColor.set(backgroundColor, CACHE_ERROR)
  25. throw new Error('Invalid background color.' + backgroundColor);
  26. }
  27. const textColor = (r * 0.299 + g * 0.587 + b * 0.114) > 186 ? '#000' : '#FFF'
  28. // 缓存数据
  29. colorByBgColor.set(backgroundColor, textColor)
  30. return textColor
  31. }

完整代码可以在代码库中 转换问题颜色[1] 中看到。

当然了,如果你不需要严格遵循 W3C 准则,当前代码已经足够使用。但是如果你需要严格遵循你可以参考 http://stackoverflow.com/a/3943023/112731 以及 https://www.w3.org/TR/WCAG20/。

参考资料

[1]

转换问题颜色: https://github.com/wsafight/Daily-Algorithm/blob/master/src/fun/contrast-text-color.ts

[2]

stackoverflow 问题: http://stackoverflow.com/a/3943023/112731

最后

  • 欢迎加我微信(winty230),拉你进技术群,长期交流学习…

  • 欢迎关注「前端Q」,认真学前端,做个专业的技术人…

format_png 1

format_png 2

点个在看支持我吧

format_png 3

发表评论

表情:
评论列表 (有 0 条评论,223人围观)

还没有评论,来说两句吧...

相关阅读

    相关 css背景适应

    在开发时,修改了d2admin的登录页面。使用了背景图片,但是ui给的图过于大(可能是我电脑屏幕小哈)无法完整的显示到页面上,所以修改了代码,可以完整显示背景图。 代码如下: