使用JavaScript创建基于字符串的十六进制颜色

Dar*_*ght 125 javascript string hex colors

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

甚至可能是简写的十六进制值(例如:),#FFF如果那不那么复杂的话.事实上,来自"网页安全"调色板的颜色将是理想的选择.

Joe*_*man 161

以下是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;
}
Run Code Online (Sandbox Code Playgroud)

用法:

stringToColour("greenish");
// -> #9bc63b
Run Code Online (Sandbox Code Playgroud)

例:

http://jsfiddle.net/sUK45/

(替代/更简单的解决方案可能涉及返回'rgb(...)'样式的颜色代码.)

  • Upvoted正确拼写颜色 (29认同)
  • 这段代码与NoSQL自动生成的ID一起使用非常棒,每次对同一个用户来说颜色都是一样的. (3认同)
  • 谢谢!对此的适应仅从字符串生成柔和/明亮的颜色/sf/answers/4514360441/ (2认同)

Cri*_*hez 145

只需将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;
}
Run Code Online (Sandbox Code Playgroud)

转换你会做:

intToRGB(hashCode(your_string))
Run Code Online (Sandbox Code Playgroud)

  • 我正在将一堆音乐类型标签转换为背景颜色,这为我节省了大量时间. (2认同)
  • 对于相似的字符串,我在使用几乎相同的颜色时遇到一些问题,例如:`intToRGB(hashCode('hello1'))-&gt;“ 3A019F”``intToRGB(hashCode('hello2'))-&gt;“ 3A01A0”`通过为最终哈希值添加乘法来添加代码:`return 100 * hash;` (2认同)

Thy*_*ine 40

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

另请参阅如何自动生成N"不同"颜色?更多类似的替代品.

function colorByHashCode(value) {
    return "<span style='color:" + value.getHashCode().intToHSL() + "'>" + value + "</span>";
}
String.prototype.getHashCode = function() {
    var hash = 0;
    if (this.length == 0) return hash;
    for (var i = 0; i < this.length; i++) {
        hash = this.charCodeAt(i) + ((hash << 5) - hash);
        hash = hash & hash; // Convert to 32bit integer
    }
    return hash;
};
Number.prototype.intToHSL = function() {
    var shortened = this % 360;
    return "hsl(" + shortened + ",100%,30%)";
};

document.body.innerHTML = [
  "javascript",
  "is",
  "nice",
].map(colorByHashCode).join("<br/>");
Run Code Online (Sandbox Code Playgroud)
span {
  font-size: 50px;
  font-weight: 800;
}
Run Code Online (Sandbox Code Playgroud)

在HSL中它的色调,饱和度,亮度.因此0-359之间的色调将获得所有颜色,饱和度是你想要的颜色有多丰富,100%适合我.而亮度决定了深度,50%是正常的,25%是深色,75%是柔和的.我有30%,因为它最适合我的配色方案.

  • 一个非常通用的解决方案. (3认同)
  • 感谢您分享解决方案,您可以在其中决定颜色的色彩! (2认同)

Kyl*_*ley 13

使用hashCodeCristian Sanchez 的答案hsl和现代 javascript,您可以创建一个具有良好对比度的颜色选择器,如下所示:

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

function pickColor(str) {
  return `hsl(${hashCode(str) % 360}, 100%, 80%)`;
}

one.style.backgroundColor = pickColor(one.innerText)
two.style.backgroundColor = pickColor(two.innerText)
Run Code Online (Sandbox Code Playgroud)
div {
  padding: 10px;
}
Run Code Online (Sandbox Code Playgroud)
<div id="one">One</div>
<div id="two">Two</div>
Run Code Online (Sandbox Code Playgroud)

由于它是 hsl,您可以缩放亮度以获得所需的对比度。

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

function pickColor(str) {
  // Note the last value here is now 50% instead of 80%
  return `hsl(${hashCode(str) % 360}, 100%, 50%)`;
}

one.style.backgroundColor = pickColor(one.innerText)
two.style.backgroundColor = pickColor(two.innerText)
Run Code Online (Sandbox Code Playgroud)
div {
  color: white;
  padding: 10px;
}
Run Code Online (Sandbox Code Playgroud)
<div id="one">One</div>
<div id="two">Two</div>
Run Code Online (Sandbox Code Playgroud)


Asl*_*lam 12

这是我的 2021 版本,带有 Reduce Function 和 HSL Color。

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


Ric*_*ith 9

我发现生成随机颜色往往会产生对我的口味没有足够对比度的颜色.我发现最容易解决的方法是预先填充一个非常不同颜色的列表.对于每个字符串,指定列表中的下一个颜色:

// 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");
Run Code Online (Sandbox Code Playgroud)

虽然这只有64种颜色的限制,但我发现大多数人无论如何都无法真正区分它们.我想你总能添加更多颜色.

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

颜色列表已经从这个SO答案解除,还有其他列表有更多的颜色.


Vir*_*ngh 7

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)}`;
}
Run Code Online (Sandbox Code Playgroud)


Jos*_*rra 6

我已经向Please.js打开了一个pull请求,允许从哈希生成颜色.

您可以将字符串映射到这样的颜色:

const color = Please.make_color({
    from_hash: "any string goes here"
});
Run Code Online (Sandbox Code Playgroud)

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


Nat*_*han 5

如果输入的差异不足以使简单的哈希使用整个色谱,则可以使用种子随机数生成器代替哈希函数。

我正在使用乔·弗里曼(Joe Freeman)的答案中的颜色编码器,以及大卫·鲍(David Bau)的种子随机数生成器

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;
}
Run Code Online (Sandbox Code Playgroud)


est*_*ani 5

随机颜色的另一种解决方案:

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;
}
Run Code Online (Sandbox Code Playgroud)

对我而言,这是混杂的事情。我从这里使用了JFreeman Hash函数(也是该线程的答案)和Asykäri伪随机函数,并从我自己那里使用一些填充和数学。

我怀疑该功能会产生均匀分布的颜色,尽管它看起来不错并且可以做到。


Rob*_*arp 5

这是我想出的一个解决方案,用于根据输入字符串生成美观的柔和色彩。它使用字符串的前两个字符作为随机种子,然后根据该种子生成 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 };
}
Run Code Online (Sandbox Code Playgroud)

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


归档时间:

查看次数:

76215 次

最近记录:

6 年,1 月 前