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

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


当前回答

这个函数很有用。这是一个改编,相当长的执行这个repo ..

const color = (str) => {
    let rgb = [];
    // Changing non-hexadecimal characters to 0
    str = [...str].map(c => (/[0-9A-Fa-f]/g.test(c)) ? c : 0).join('');
    // Padding string with zeroes until it adds up to 3
    while (str.length % 3) str += '0';

    // Dividing string into 3 equally large arrays
    for (i = 0; i < str.length; i += str.length / 3)
        rgb.push(str.slice(i, i + str.length / 3));

    // Formatting a hex color from the first two letters of each portion
    return `#${rgb.map(string => string.slice(0, 2)).join('')}`;
}

其他回答

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

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

我想要类似丰富的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%,因为它最适合我的配色方案。

在看了相当密集的代码和相当古老的答案之后,我想我应该从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>

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

我的代码是Java的。

谢谢你做的一切。

public static int getColorFromText(String text)
    {
        if(text == null || text.length() < 1)
            return Color.BLACK;

        int hash = 0;

        for (int i = 0; i < text.length(); i++)
        {
            hash = text.charAt(i) + ((hash << 5) - hash);
        }

        int c = (hash & 0x00FFFFFF);
        c = c - 16777216;

        return c;
    }

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

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伪随机函数,以及我自己的一些填充和数学。

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