代码之家  ›  专栏  ›  技术社区  ›  Joseph

仅在React和JS中生成深色

  •  0
  • Joseph  · 技术社区  · 1 年前

    我有一个 <Avatar/> 组件,其中的文本是彩色的 white , 如何确保其背景颜色为深色,以便在动态生成后可以看到文本?

    Codesandbox -----> CLICK HERE

    代码:

      const colors = useMemo(() => {
        const randomColors = persons.map(() => `#${Math.floor(Math.random() * 16777215).toString(16)}`);
        return randomColors;
      }, [persons]);
    
    2 回复  |  直到 1 年前
        1
  •  1
  •   Mina    1 年前
    1. 每个颜色成分(红色、绿色、蓝色)的随机值为0-255。您需要限制为0-127以确保生成的颜色较暗。

    2. padStart(2, '0') 确保每个组件都有两个十六进制形式的数字

    utils.js

    export function randomColors(persons) {
      const darkColors = persons.map(() => {
            // Generate each color component in the lower half (0-127) of the 0-255 range
            const r = Math.floor(Math.random() * 128).toString(16).padStart(2, '0');
            const g = Math.floor(Math.random() * 128).toString(16).padStart(2, '0');
            const b = Math.floor(Math.random() * 128).toString(16).padStart(2, '0');
            return `#${r}${g}${b}`;
      });
      return darkColors;
    }
    

    在你的反应组件内部。

    const colors = useMemo(() => {
        return randomColors(persons)
    }, [persons]);
    

    CODESANDBOX

        2
  •  0
  •   Maryum khan    1 年前

    您需要检查颜色的亮度,然后进行相应的调整

      const randomColors = persons.map(() => {
                  let color = `#${Math.floor(Math.random() * 16777215).toString(16)}`;
            
                  while (isLight(color)) { //check if color is dark enough
                    color = `#${Math.floor(Math.random() * 16777215).toString(16)}`;
                  }
            
                  return color;
                });
            
                return randomColors;
              }, [persons]);
            
              function isLight(color) {
                const hex = color.replace('#', '');
                const r = parseInt(hex.substr(0, 2), 16);
                const g = parseInt(hex.substr(2, 2), 16);
                const b = parseInt(hex.substr(4, 2), 16);
            
            //calculate luminance
                const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
                return luminance > 150;
              }