If you don't want o reinvent the wheel, now we have some libraries to do this task.
Avatar: is a JavaScript library for showing Gravatars or generating user avatars. This one provides a plenty of options to do the task in the front end.
import Avatar from 'avatar-initials';
const avatar = new Avatar(document.getElementById('avatar'), {
useGravatar: true, // Allow Gravatars or not.
fallbackImage: '', // URL or Data URI used when no initials are provided and not using Gravatars.
size: 80, // Size in pixels, fallback for hidden images and Gravatar
// Initial Avatars Specific
initials: '', // Initials to be used.
initial_fg: '#888888', // Text Color
initial_bg: '#f4f6f7', // Background Color
initial_size: null, // Text Size in pixels
initial_weight: 100, // Font weight (numeric value for light, bold, etc.)
initial_font_family: "'Lato', 'Lato-Regular', 'Helvetica Neue'",
// Gravatar Specific
hash: null, // Precalculated MD5 string of an email address
email: null, // Email used for the Gravatar
fallback: 'mm', // Fallback Type
rating: 'x', // Gravatar Rating
forcedefault: false, // Force Gravatar Defaults
allowGravatarFallback: false, // Use Gravatars fallback, not fallbackImage
// GitHub Specific
github_id: null, // GitHub User ID.
// Avatars.io Specific
use_avatars_io: false, // Enable Avatars.io Support
avatars_io: {
user_id: null, // Avatars.io User ID
identifier: null, // Avatars.io Avatar Identifier
twitter: null, // Twitter ID or Username
facebook: null, // Facebook ID or Username
instagram: null, // Instagram ID or Username
size: 'medium', // Size: small, medium, large
},
setSourceCallback: null, // Callback called when image source is set (useful to cache avatar sources provided by third parties such as Gravatar)
});
No Avatar: Node.js Module and Express middleware to generate avatar image with initials in the back end. What you have to do is to build an object with options to choose text, colors and size of the image.
const { save } = require('no-avatar');
const savePath = __dirname + '/avatar.png';
const options = {
width: 150,
height: 150,
text: userInitials,
bgColor: 000000,
fontColor: FFFFFF,
fontSize: 60
};
save(savePath, options, function(err){
if(err) return console.log(err);
return console.log('avatar.png saved at path ' + savePath);
});