【问题标题】:Make sense color for word使单词有意义的颜色
【发布时间】:2021-03-15 10:54:27
【问题描述】:

我们有 A-z 字符和 abcdef0-9 颜色。

我需要在同一个单词上始终使用相同的颜色,(苹果始终是红色,汽车始终是绿色,汽车-始终是橙色)-即使单词有 1 或 3 个字母,我也希望每次都看到相同的颜色。 在我的函数中,如果没有数学颜色的字母,我有随机函数。

请帮我升级功能并将数学随机替换为 get letter index in alphabet divide on colors char position 或其他内容

export function MakeSenseColor(str) {
  if(!str && typeof str !== 'string') return '';

  const chars1 = 'abc6789';
  const chars2 = 'abcdef0123456789';

  const Digits = 'qйwцeуrкtеyнuгiшoщpзaхsъdфfыgвhаjпkрlоzлxдcжvэbяnчmсмитьбю1234567890';
  const splittedStr = str.split('').map((s,i,arr) => {
    const charPos = s && (Digits.split('')).indexOf(`${s}`.toLowerCase());

    if(!charPos || charPos === -1) return '0';

    if (charPos >= 0 ) {
      const char = (charPos * chars2.length) / Digits.length
      const charColor = (char * 6) / arr.length;

      return chars2[parseInt(charColor)];
    }

    return '0';
  });

  let color = '#';

  for (let i = 0; color.length < 7; i++) {
    const add = splittedStr[i%6] || chars1.charAt(Math.floor(Math.random() * chars1.length))

    color = color + add;
  }

  return color;
}

【问题讨论】:

    标签: javascript math random colors


    【解决方案1】:

    我只需hash 字符串并使用它来生成指示颜色的十六进制字符串。 https://stackoverflow.com/a/52171480/1358308 这里的哈希实现对我来说看起来相对不错。

    // borrowed from https://stackoverflow.com/a/52171480/1358308
    function cyrb53(str, seed = 0) {
        let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
        for (let i = 0, ch; i < str.length; i++) {
            ch = str.charCodeAt(i);
            h1 = Math.imul(h1 ^ ch, 2654435761);
            h2 = Math.imul(h2 ^ ch, 1597334677);
        }
        h1 = Math.imul(h1 ^ (h1>>>16), 2246822507) ^ Math.imul(h2 ^ (h2>>>13), 3266489909);
        h2 = Math.imul(h2 ^ (h2>>>16), 2246822507) ^ Math.imul(h1 ^ (h1>>>13), 3266489909);
        return 4294967296 * (2097151 & h2) + (h1>>>0);
    };
    
    function MakeSenseColor(str) {
        // hash the string and convert to hex
        let hash = cyrb53(str).toString(16);
    
        // just use the last 6 characters and prepend character to indicate color
        return '#' + hash.slice(-6);
    }
    

    这给了我独特而一致的结果:

    • '苹果' = #002f86
    • '汽车' = #684a21
    • '汽车' = #c10e83

    这些颜色与您在问题中指出的颜色不同,但我想您可以硬编码一些您关心的颜色。

    【讨论】:

    • 我不需要硬编码,因为我的话很不一样。而且因为此功能仅用于 App 中的乐趣/情感。但是,我需要的是来自单词的哈希。然后我可以使用哈希转换为颜色。我认为 hash.slice 给出了非常重复的颜色。但这是一个很好的答案。谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-14
    相关资源
    最近更新 更多