Skip to content

Instantly share code, notes, and snippets.

@muhghazaliakbar
Last active March 27, 2020 13:08
Show Gist options
  • Save muhghazaliakbar/8ab87e59558faede3a370e31a4a04db5 to your computer and use it in GitHub Desktop.
Save muhghazaliakbar/8ab87e59558faede3a370e31a4a04db5 to your computer and use it in GitHub Desktop.
import React from 'react'
interface AvatarProps {
username: string
initials?: string
size?: number
src?: string
rounded?: boolean
classes?: string
}
const avatarPropsDefault = {
initials: '',
size: 200,
rounded: true,
src: '',
classes: 'rounded-full w-8 h-8 border-2'
}
const Avatar = (props: AvatarProps) => {
const avatarData = { ...avatarPropsDefault, ...props }
const getDataURI = (name: string, size: number) => {
name = name || ''
size = size || 60
const colours = [
'#1abc9c',
'#2ecc71',
'#3498db',
'#9b59b6',
'#34495e',
'#16a085',
'#27ae60',
'#2980b9',
'#8e44ad',
'#2c3e50',
'#f1c40f',
'#e67e22',
'#e74c3c',
'#ecf0f1',
'#95a5a6',
'#f39c12',
'#d35400',
'#c0392b',
'#bdc3c7',
'#7f8c8d'
]
const nameSplit = String(name)
.toUpperCase()
.split(' ')
const charCodeSum = name
.split('')
.map(c => {
return c.charCodeAt(0)
})
.reduce((a, b) => a + b, 0)
let initials, canvas, dataURI, context
if (nameSplit.length === 1) {
initials = nameSplit[0] ? nameSplit[0].charAt(0) : '?'
} else {
initials = nameSplit[0].charAt(0) + nameSplit[1].charAt(0)
}
if (window.devicePixelRatio) {
size = size * window.devicePixelRatio
}
const charIndex = (initials === '?' ? 72 : charCodeSum) - 64
const colourIndex = charIndex % colours.length
canvas = document.createElement('canvas')
canvas.width = size
canvas.height = size
// eslint-disable-next-line prefer-const
context = canvas.getContext('2d')
context.fillStyle = colours[colourIndex]
context.fillRect(0, 0, canvas.width, canvas.height)
context.font = 'bold ' + Math.round(canvas.width / 2) + 'px "Lato"'
context.textAlign = 'center'
context.fillStyle = '#FFF'
context.fillText(initials, size / 2, size / 1.5)
// eslint-disable-next-line prefer-const
dataURI = canvas.toDataURL()
canvas = null
return dataURI
}
const getImage = () => {
if (avatarData.src) {
return avatarData.src
} else {
return getDataURI(avatarData.username, avatarData.size)
}
}
return (
<div>
<img className={avatarData.classes} src={getImage()} alt={avatarData.username}/>
</div>
)
}
export default Avatar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment