Skip to content

Instantly share code, notes, and snippets.

@dorianbayart
Created October 26, 2022 22:36
Show Gist options
  • Save dorianbayart/d92bbdf222fd7e602087ce0b550bc355 to your computer and use it in GitHub Desktop.
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
// 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