Created
October 26, 2022 22:36
-
-
Save dorianbayart/d92bbdf222fd7e602087ce0b550bc355 to your computer and use it in GitHub Desktop.
Generate a color from a string - Calculate a Hash of a String and use it to generate HSL(A) 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
// Utils - Calculate a Hash of a String | |
const hashCode = (str) => { | |
let hash = 0 | |
for (var i = 0; i < str.length; i++) { | |
hash = str.charCodeAt(i) + ((hash << 5) - hash) | |
} | |
return hash | |
} | |
// Generate a HSL color using the Hash | |
const getColorFromString = (str) => { | |
return `hsl(${hashCode(str) % 360}, 100%, 45%)` | |
} | |
// Generate a HSLA color using the Hash - with a transparency parameter [0, 1] | |
const getColorFromStringWithTransparency = (str, transparency) => { | |
return `hsla(${hashCode(str) % 360}, 100%, 45%, ${transparency})` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment