Skip to content

Instantly share code, notes, and snippets.

@axetroy

axetroy/str2color.js

Last active May 29, 2020
Embed
What would you like to do?
根据一个字符串,生成一个动态的hex颜色
var stringToColor = function(str) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
var color = '#';
for (var i = 0; i < 3; i++) {
var value = (hash >> (i * 8)) & 0xFF;
color += ('00' + value.toString(16)).substr(-2);
}
return color;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment