Skip to content

Instantly share code, notes, and snippets.

@yi
Created May 12, 2014 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yi/9151fdd93883c7b7f106 to your computer and use it in GitHub Desktop.
Save yi/9151fdd93883c7b7f106 to your computer and use it in GitHub Desktop.
JS: generate a color value from arbitery given string
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 intToARGB(i){
var resualt = ""
var str = ((i>>24)&0xFF).toString(16);
if(str.length < 2)str = "0"+str;
resualt += str;
str = ((i>>16)&0xFF).toString(16);
if(str.length < 2)str = "0"+str;
resualt += str;
str = ((i>>8)&0xFF).toString(16);
if(str.length < 2)str = "0"+str;
resualt += str;
return resualt;
}
var color = intToARGB(hashCode("xwr中文opoops怎发发么样?"))
$("#koko").css("background-color", "#"+color)
$("#koko").text(color)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment