Created
October 23, 2023 13:12
-
-
Save erdesigns-eu/7d75a23030c7b0d30db3d2b998235094 to your computer and use it in GitHub Desktop.
Generate colors based on initials (for use in avatar)
This file contains hidden or 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
// Generate a color based on letters. | |
export const generateColor = (letters) => { | |
// Generate a simple hash from a string | |
const getHashOfString = (str) => { | |
let hash = 0; | |
for (let i = 0; i < str.length; i++) { | |
hash = str.charCodeAt(i) + ((hash << 5) - hash); | |
} | |
hash = Math.abs(hash); | |
return hash; | |
}; | |
// Normalize a hash to a range | |
const normalizeHash = (hash, min, max) => { | |
return Math.floor((hash % (max - min)) + min); | |
}; | |
// Update these ranges to generate different colors | |
const hRange = [0, 360]; // Hue range | |
const sRange = [50, 70]; // Saturation range | |
const lRange = [40, 60]; // Lightness range | |
// Generate a HSL color from a string | |
const generateHSL = (str) => { | |
const hash = getHashOfString(str); | |
const h = normalizeHash(hash, hRange[0], hRange[1]); | |
const s = normalizeHash(hash, sRange[0], sRange[1]); | |
const l = normalizeHash(hash, lRange[0], lRange[1]); | |
return [h, s, l]; | |
}; | |
// Convert HSL to string | |
const HSLtoString = (hsl) => { | |
return `hsl(${hsl[0]}, ${hsl[1]}%, ${hsl[2]}%)`; | |
}; | |
return HSLtoString(generateHSL(letters)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment