Created
February 3, 2018 18:35
-
-
Save schie/95479ac8e039dcef5fcc76696c7aea9c to your computer and use it in GitHub Desktop.
Converting a random string to a hex color
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function stringTColor(str) { | |
let hash = 0; | |
for (let i = 0; i < str.length; i++) { | |
hash = str.charCodeAt(i) + ((hash << 5) - hash); | |
} | |
let color = '#'; | |
for (let i = 0; i < 3; i++) { | |
let value = (hash >> (i * 8)) & 0xFF; | |
color += ('00' + value.toString(16)).substr(-2); | |
} | |
return color; | |
} | |
stringToColor('greenish') // #9bc63b | |
stringToColor('test') // #924436 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment