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

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


当前回答

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)}`;
}

其他回答

我的代码是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;
    }

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

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

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

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

如果您的输入差异不足以让一个简单的哈希使用整个颜色光谱,您可以使用一个种子随机数生成器而不是哈希函数。

我用的是乔·弗里曼的答案中的颜色编码器,还有大卫·鲍的种子随机数生成器。

function stringToColour(str) {
    Math.seedrandom(str);
    var rand = Math.random() * Math.pow(255,3);
    Math.seedrandom(); // don't leave a non-random seed in the generator
    for (var i = 0, colour = "#"; i < 3; colour += ("00" + ((rand >> i++ * 8) & 0xFF).toString(16)).slice(-2));
    return colour;
}

下面是我提出的一个解决方案,根据输入字符串生成美观的粉彩颜色。它使用字符串的前两个字符作为随机种子,然后基于该种子生成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