基于带JavaScript的字符串创建十六进制颜色 [英] Create a hexadecimal colour based on a string with JavaScript
问题描述
我想创建一个函数来接受任何旧的字符串(通常是单个单词),并从以某种方式生成#000000
和 #FFFFFF
,因此我可以将其用作HTML元素的颜色。
I want to create a function that will accept any old string (will usually be a single word) and from that somehow generate a hexadecimal value between #000000
and #FFFFFF
, so I can use it as a colour for a HTML element.
如果不那么复杂,甚至可以是一个速记十六进制值(例如: #FFF
)。实际上,来自网络安全调色板的颜色将是理想的。
Maybe even a shorthand hex value (e.g: #FFF
) if that's less complicated. In fact, a colour from a 'web-safe' palette would be ideal.
推荐答案
href =http://stackoverflow.com/questions/2464745/compute-hex-color-code-for-an-arbitrary-string>计算任意字符串的十六进制颜色代码到Javascript:
Just porting over the Java from Compute hex color code for an arbitrary string to 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;
}
要进行转换,请执行以下操作:
To convert you would do:
intToRGB(hashCode(your_string))
这篇关于基于带JavaScript的字符串创建十六进制颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!