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

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


当前回答

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

其他回答

我发现随机生成的颜色往往没有足够的对比度来满足我的口味。我发现解决这个问题最简单的方法是预先填充一个非常不同的颜色列表。对于每个新字符串,分配列表中的下一个颜色:

// Takes any string and converts it into a #RRGGBB color.
var StringToColor = (function(){
    var instance = null;

    return {
    next: function stringToColor(str) {
        if(instance === null) {
            instance = {};
            instance.stringToColorHash = {};
            instance.nextVeryDifferntColorIdx = 0;
            instance.veryDifferentColors = ["#000000","#00FF00","#0000FF","#FF0000","#01FFFE","#FFA6FE","#FFDB66","#006401","#010067","#95003A","#007DB5","#FF00F6","#FFEEE8","#774D00","#90FB92","#0076FF","#D5FF00","#FF937E","#6A826C","#FF029D","#FE8900","#7A4782","#7E2DD2","#85A900","#FF0056","#A42400","#00AE7E","#683D3B","#BDC6FF","#263400","#BDD393","#00B917","#9E008E","#001544","#C28C9F","#FF74A3","#01D0FF","#004754","#E56FFE","#788231","#0E4CA1","#91D0CB","#BE9970","#968AE8","#BB8800","#43002C","#DEFF74","#00FFC6","#FFE502","#620E00","#008F9C","#98FF52","#7544B1","#B500FF","#00FF78","#FF6E41","#005F39","#6B6882","#5FAD4E","#A75740","#A5FFD2","#FFB167","#009BFF","#E85EBE"];
        }

        if(!instance.stringToColorHash[str])
            instance.stringToColorHash[str] = instance.veryDifferentColors[instance.nextVeryDifferntColorIdx++];

            return instance.stringToColorHash[str];
        }
    }
})();

// Get a new color for each string
StringToColor.next("get first color");
StringToColor.next("get second color");

// Will return the same color as the first time
StringToColor.next("get first color");

虽然它的颜色限制只有64种,但我发现大多数人在那之后都无法真正分辨出区别。我认为你可以添加更多的颜色。

虽然这段代码使用了硬编码的颜色,但至少可以保证您在开发过程中确切地知道在生产中您将看到的颜色之间的对比有多大。

颜色列表是从这个SO答案中提取的,还有其他更多颜色的列表。

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

以下是对CD Sanchez的答案的改编,它始终返回一个6位数的颜色代码:

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

用法:

stringToColour("greenish");
// -> #9bc63b

例子:

http://jsfiddle.net/sUK45/

(另一种/更简单的解决方案可能涉及返回'rgb(…)'风格的颜色代码。)

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

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';
}

}

只是将Java从Compute的十六进制颜色代码任意字符串移植到Javascript:

function hashCode(str) { // java String#hashCode
    var hash = 0;
    for (var i = 0; i < str.length; i++) {
       hash = str.charCodeAt(i) + ((hash << 5) - hash);
    }
    return hash;
} 

function intToRGB(i){
    var c = (i & 0x00FFFFFF)
        .toString(16)
        .toUpperCase();

    return "00000".substring(0, 6 - c.length) + c;
}

转换你会做:

intToRGB(hashCode(your_string))