我想创建一个函数,它将接受任何旧字符串(通常是一个单词),并从中以某种方式生成一个十六进制值在#000000和#FFFFFF之间,所以我可以使用它作为HTML元素的颜色。

如果不那么复杂的话,甚至可能是一个简化的十六进制值(例如:#FFF)。事实上,“网络安全”调色板中的颜色是最理想的。


当前回答

这是我2021年的版本,带有还原功能和HSL颜色。

function getBackgroundColor(stringInput) {
    let stringUniqueHash = [...stringInput].reduce((acc, char) => {
        return char.charCodeAt(0) + ((acc << 5) - acc);
    }, 0);
    return `hsl(${stringUniqueHash % 360}, 95%, 35%)`;
}

其他回答

我已经打开了一个pull request to Please.js,它允许从散列中生成颜色。

你可以像这样将字符串映射到一个颜色:

const color = Please.make_color({
    from_hash: "any string goes here"
});

例如,"any string goes here"将返回"#47291b" “another!”返回为“#1f0c3d”

Javascript解决方案受到Aslam的解决方案的启发,但返回十六进制颜色代码的颜色

/**
 * 
 * @param {String} - stringInput - 'xyz'
 * @returns {String} - color in hex color code - '#ae6204'
 */
function getBackgroundColor(stringInput) {
    const h = [...stringInput].reduce((acc, char) => {
        return char.charCodeAt(0) + ((acc << 5) - acc);
    }, 0);
    const s = 95, l = 35 / 100;
    const a = s * Math.min(l, 1 - l) / 100;
    const f = n => {
        const k = (n + h / 30) % 12;
        const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
        return Math.round(255 * color).toString(16).padStart(2, '0');   // convert to Hex and prefix "0" if needed
    };
    return `#${f(0)}${f(8)}${f(4)}`;
}

下面是另一个尝试:

function stringToColor(str){
  var hash = 0;
  for(var i=0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 3) - hash);
  }
  var color = Math.abs(hash).toString(16).substring(0, 6);

  return "#" + '000000'.substring(0, 6 - color.length) + color;
}

我想要类似丰富的HTML元素的颜色,我惊讶地发现CSS现在支持hsl()颜色,所以一个完整的解决方案如下:

另参见如何自动生成N“不同”的颜色?更多类似的选择。

编辑:根据@zei的版本更新(美式拼写)

var stringToColor = (string, saturation = 100, lightness = 75) => { let hash = 0; for (let i = 0; i < string.length; i++) { hash = string.charCodeAt(i) + ((hash << 5) - hash); hash = hash & hash; } return `hsl(${(hash % 360)}, ${saturation}%, ${lightness}%)`; } // For the sample on stackoverflow function colorByHashCode(value) { return "<span style='color:" + stringToColor(value) + "'>" + value + "</span>"; } document.body.innerHTML = [ "javascript", "is", "nice", ].map(colorByHashCode).join("<br/>"); span { font-size: 50px; font-weight: 800; }

在HSL中,它的色调,饱和度,亮度。所以色调在0-359之间会得到所有的颜色,饱和度是你想要的颜色的丰富程度,100%对我来说是合适的。而亮度决定了深度,50%是正常的,25%是深色,75%是粉彩。我有30%,因为它最适合我的配色方案。

2023版本普通和简单的TypeScript箭头函数,返回HSL颜色。

const stringToColor = (value: string) => {
  let hash = 0;
  for (let i = 0; i < value.length; i++) {
    hash = value.charCodeAt(i) + ((hash << 5) - hash);
  }

  return `hsl(${hash % 360}, 85%, 35%)`;
};