Last active
May 31, 2021 16:04
-
-
Save nixjs/df2e25d265aa5005bcde0da9c7279657 to your computer and use it in GitHub Desktop.
Generate color by name
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
import CryptoJS from 'crypto-js'; | |
const toHue = value => { | |
let hash = 0; | |
if (value.length === 0) return hash; | |
for (let i = 0; i < value.length; i += 1) { | |
hash = value.charCodeAt(i) + ((hash << 5) - hash); | |
hash = hash & hash; | |
} | |
return hash % 360; | |
}; | |
const getBackgroundColor = (str) => { | |
const hex = CryptoJS.MD5(str); | |
if (hex) { | |
const prefix = Math.abs(toHue(hex.toString())); | |
switch (true) { | |
case prefix > 0 && prefix <= 45: | |
return '#F29B4C'; | |
case prefix > 45 && prefix <= 95: | |
return '#FFD661'; | |
case prefix > 95 && prefix <= 145: | |
return '#2DB84C'; | |
case prefix > 145 && prefix <= 180: | |
return '#21D6AA'; | |
case prefix > 180 && prefix <= 240: | |
return '#22A1D3'; | |
case prefix > 240 && prefix <= 310: | |
return '#AE56D8'; | |
case prefix > 310 && prefix <= 340: | |
return '#EF549B'; | |
case prefix > 340 && prefix <= 360: | |
return '#F25A5A'; | |
default: | |
return '#F25A5A'; | |
} | |
} | |
return '#F25A5A'; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment