Avatars create a digital representation of a user and are usually used in web profiles. Most of the time a user is required to upload an image and then used it as the profile. An example of this is Google Mail Services. When a user does not upload a profile image an avatar is generated using his/her initials. Are you curious about how this magic happens? Don’t worry I’ve got you covered. In this article, we are going to explore how we can generate avatars based on user initials.
Codesandbox
The final version of this project can be viewed on Codesandbox.
## GithubCheck out the complete source code in this GitHub Repository.
Pre-requisites
To follow along through this article you are required to have:
Basic knowledge of HTML
Knowledge of Javascript
Some knowledge of Bootstrap
Introduction
In this article, we are going to use HTML5, Bootstrap UI framework, and JavaScript to create an application that allows users to generate avatars using their names and the colors of their choice.
Sample Project Setup
In this article, I will need you to clone the project from GitHub
1git clone https://github.com/musebe/Avatars-JavaScript23cd Avatars-JavaScript
In your favorite text editor, open the Avatars-JavaScript
folder, right-click index.html
, and open the file in your browser. You should be able to see this page after you enter your name, choose your favorite colors, and click generate.
Usage
Let us now examine the index.js
to understand the functionality behind this application.
1function generateAvatar(23text,45foregroundColor = "white",67backgroundColor = "black"89) {1011const canvas = document.createElement("canvas");1213download = document.getElementById("download");1415const context = canvas.getContext("2d");16171819canvas.width = 200;2021canvas.height = 200;22232425// Draw background2627context.fillStyle = backgroundColor;2829context.fillRect(0, 0, canvas.width, canvas.height);30313233// Draw text3435context.font = "bold 100px Assistant";3637context.fillStyle = foregroundColor;3839context.textAlign = "center";4041context.textBaseline = "middle";4243context.fillText(text, canvas.width / 2, canvas.height / 2 );4445download.href=canvas.toDataURL("image/png");4647return canvas.toDataURL("image/png");4849}
Create the Canvas Element
The generateAvatar()
function takes three parameters that is the text
, foregroundColor
and backgroundColor
. We are going to use createElement method to create a canvas element in our HTML document.
createElement() method creates an element specified by tagName
HTML canvas is an element that can be used to draw graphics on a web page via scripting (usually JavaScript)
1const canvas = document.createElement("canvas");
Draw the background
To get a drawing context on the canvas we use the HTMLCanvasElement.getContext()
method and takes a contextType parameter getContext(contextType)
for our case "2d"
which leads to the creation of an object representing a two-dimensional rendering context.
1const context = canvas.getContext("2d");
We can also specify the height pixels and width pixels of our canvas element by using the height and width attribute of the canvas element created.
1canvas.width = 200;23canvas.height = 200;
We can then draw our background by first setting the background color by using the fillStyle
property and then drawing a filled rectangle with the background set.
The fillStyle canvas property sets the color used in filling the drawing.
The fillRect() method draws a filled rectangle. The default background color is black.
The fillRect()
takes four parameters, the x-coordinate of the upper corner of the rectangle, the y-coordinate of the upper corner of the rectangle, the width of the rectangle in pixels, and the height of the rectangle in pixels.
1// this is the syntax: context.fillRect(x, y, width, height);23// in our code context.fillrect(0, 0, 200, 200)45context.fillRect(0, 0, canvas.width, canvas.height);
Draw the text
To draw the text inside our canvas element we have to set the font using the font
property, fill the text with color using the fillStyle
property, text-align our text using the textAlign
property, set the baseline used when drawing the text using text baseline
property and draw our text on the canvas using fillText()
method.
1context.font = "bold 100px Assistant";23context.fillStyle = foregroundColor;45context.textAlign = "center";67context.textBaseline = "middle";89// context.fillText( text, x, y);1011context.fillText(text, canvas.width / 2, canvas.height / 2 ); // (text, 100, 100)
We can then return a data URL containing the representation of the image in the format specified by the type parameter in our case `image/png. To enable the user to download the avatar image we specify the target as the data URL of the image.
1download.href=canvas.toDataURL("image/png");23return canvas.toDataURL("image/png");
Get inputs from the user
We can get the values for full name, background color, and text color from the user. so we can use them as arguments to the generateAvatar()
method. The generate() method wil do this for us and will be called once the generate
button is clicked.
1var name= document.getElementById("name").value;23var bcgColor= document.getElementById("bcg-color").value;45var textColor= document.getElementById("text-color").value;
After getting the name of our user we can get the initials by first splitting the string using split(" ")
then we get the first character from the first element and the last element. We then ensure that our initials are in uppercase.
1const myNames = name.split(" ");23const initials = myNames.shift().charAt(0) + myNames.pop().charAt(0);45const nameInitials =initials.toUpperCase();
Since we defined our avatar div to be of style display: none
we can now show it and call the generated avatar method passing the values from the user.
1var avatarDiv = document.getElementById("avatarDiv");23if (avatarDiv.style.display === "none"){45avatarDiv.style.display = "block";67}89document.getElementById("avatar").src = generateAvatar(1011nameInitials,1213textColor,1415bcgColor1617);
Conclusion
In this article, we have learned how we can generate avatars based on the user's name. Its usefulness is the ability to automatically generate avatars even when the user has not uploaded a profile image.
This can be implemented in websites or apps that have the profile of a user once he/she has logged in.