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

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


当前回答

在看了相当密集的代码和相当古老的答案之后,我想我应该从2021年的角度来回顾这个问题,只是为了好玩,希望对任何人都有用。现在有了HSL颜色模型和加密API在几乎所有浏览器(当然除了IE)中实现,它可以像这样简单地解决:

async function getColor(text, minLightness = 40, maxLightness = 80, minSaturation = 30, maxSaturation = 100) { let hash = await window.crypto.subtle.digest("SHA-1", new TextEncoder().encode(text)); hash = new Uint8Array(hash).join("").slice(16); return "hsl(" + (hash % 360) + ", " + (hash % (maxSaturation - minSaturation) + minSaturation) + "%, " + (hash % (maxLightness - minLightness) + minLightness) + "%)"; } function generateColor() { getColor(document.getElementById("text-input").value).then(color => document.querySelector(".swatch").style.backgroundColor = color); } input { padding: 5px; } .swatch { margin-left: 10px; width: 28px; height: 28px; background-color: white; border: 1px solid gray; } .flex { display: flex; } <html> <body> <div class="flex"> <form> <input id="text-input" type="text" onInput="generateColor()" placeholder="Type here"></input> </form> <div class="swatch"></div> </div> </body> </html>

这应该比手动生成散列快得多,并且还提供了一种定义饱和度和亮度的方法,以防你不想要太平或太亮或太暗的颜色(例如,如果你想在这些颜色上写文本)。

其他回答

还有一个随机颜色的解决方案:

function colorize(str) {
    for (var i = 0, hash = 0; i < str.length; hash = str.charCodeAt(i++) + ((hash << 5) - hash));
    color = Math.floor(Math.abs((Math.sin(hash) * 10000) % 1 * 16777216)).toString(16);
    return '#' + Array(6 - color.length + 1).join('0') + color;
}

对我来说,这是一种混合的工作。 我使用了JFreeman散列函数(也是这个线程中的一个答案)和Asykäri伪随机函数,以及我自己的一些填充和数学。

我怀疑该函数产生均匀分布的颜色,尽管它看起来很好,并做了它应该做的事情。

这是我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%)`;
}

下面是我提出的一个解决方案,根据输入字符串生成美观的粉彩颜色。它使用字符串的前两个字符作为随机种子,然后基于该种子生成R/G/B。

它可以很容易地扩展,以便种子是字符串中所有字符的异或,而不仅仅是前两个字符。

灵感来自David Crow的回答:算法随机生成一个美观的调色板

//magic to convert strings to a nice pastel colour based on first two chars
//
// every string with the same first two chars will generate the same pastel colour
function pastel_colour(input_str) {

    //TODO: adjust base colour values below based on theme
    var baseRed = 128;
    var baseGreen = 128;
    var baseBlue = 128;

    //lazy seeded random hack to get values from 0 - 256
    //for seed just take bitwise XOR of first two chars
    var seed = input_str.charCodeAt(0) ^ input_str.charCodeAt(1);
    var rand_1 = Math.abs((Math.sin(seed++) * 10000)) % 256;
    var rand_2 = Math.abs((Math.sin(seed++) * 10000)) % 256;
    var rand_3 = Math.abs((Math.sin(seed++) * 10000)) % 256;

    //build colour
    var red = Math.round((rand_1 + baseRed) / 2);
    var green = Math.round((rand_2 + baseGreen) / 2);
    var blue = Math.round((rand_3 + baseBlue) / 2);

    return { red: red, green: green, blue: blue };
}

GIST在这里:https://gist.github.com/ro-sharp/49fd46a071a267d9e5dd

我有一个情况,我想显示基于用户的用户名的背景,并显示用户名的第一个字母在顶部。 我使用爱的代码,它为我工作得很好

var stringToColour = function (str) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
  hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
var colour = '#';
for (var i = 0; i < 3; i++) {
  var value = (hash >> (i * 8)) & 0xff;
  colour += ('00' + value.toString(16)).substr(-2);
}
return colour;}

为了找到合适的颜色,你可以使用

function lightOrDark(color) {
// Check the format of the color, HEX or RGB?
if (color.match(/^rgb/)) {
  // If HEX --> store the red, green, blue values in separate variables
  color = color.match(
    /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/,
  );

  var r = color[1];
  var g = color[2];
  var b = color[3];
} else {
  // If RGB --> Convert it to HEX: http://gist.github.com/983661
  color = +(
    '0x' + color.slice(1).replace(color.length < 5 && /./g, '$&$&')
  );

  r = color >> 16;
  g = (color >> 8) & 255;
  b = color & 255;
}

// HSP equation from http://alienryderflex.com/hsp.html
var hsp = Math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b));

// Using the HSP value, determine whether the color is light or dark
if (hsp > 127.5) {
  return 'light';
} else {
  return 'dark';
}

}

你真正需要的是一个好的哈希函数。在节点上,我只用

const crypto = require('crypto');
function strToColor(str) {
    return '#' + crypto.createHash('md5').update(str).digest('hex').substr(0, 6);
}