Skip to content

Instantly share code, notes, and snippets.

Created May 7, 2015 15:11
Show Gist options
  • Save anonymous/890e7425f4f2748b1956 to your computer and use it in GitHub Desktop.
Save anonymous/890e7425f4f2748b1956 to your computer and use it in GitHub Desktop.
Avatar Generator from Name

Avatar Generator from Name

A name (first name and surname) is input and output using the initials from the name and a background colour (based on the first name first letter). The background colours are from from http://flatuicolors.com/

A Pen by Victor Fernandez on CodePen.

License.

function createAvatar(name, size) {
function getInitials(name) {
var nameArray = name.split(" ");
if(nameArray.length <= 1) {
return name.charAt(0).toUpperCase();
}
return nameArray[0].charAt(0).toUpperCase() + nameArray[1].charAt(0).toUpperCase();
}
function getRandomColor(colors) {
var index = Math.floor((Math.random() * colors.length) + 0);
return colors[index];
}
var colors = ["#1abc9c", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#2c3e50", "#f1c40f", "#e67e22", "#e74c3c", "#95a5a6", "#f39c12", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"];
var initials = getInitials(name);
var $elem = $('<div><span></span></div>');
var $text = $elem.find('span').text(initials);
$elem.css({
'height': size,
'width': size,
'font-size': size / 2.5,
'background': getRandomColor(colors),
'border-radius': '50%'
});
$elem.addClass('generated-avatar');
return $elem;
}
var list = [
'Pete Campbell',
'Don Draper',
'Peggy Olsen',
'Roger M. Sterling',
'Joan',
'victor@auth0.com'
];
for (person in list) {
var name = list[person],
$avatar = createAvatar(name, 60);
$('body').append($avatar);
}
.generated-avatar
position relative
display inline-block
margin 10px
span
position absolute
top 50%
left 50%
transform translate(-50%, -50%)
color white
font-family 'Proxima Nova', sans-serif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment