Generate Image Avatars with Initials in JavaScript

Eugene Musebe

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.

## Github

Check 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-JavaScript
2
3cd 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(
2
3text,
4
5foregroundColor = "white",
6
7backgroundColor = "black"
8
9) {
10
11const canvas = document.createElement("canvas");
12
13download = document.getElementById("download");
14
15const context = canvas.getContext("2d");
16
17
18
19canvas.width = 200;
20
21canvas.height = 200;
22
23
24
25// Draw background
26
27context.fillStyle = backgroundColor;
28
29context.fillRect(0, 0, canvas.width, canvas.height);
30
31
32
33// Draw text
34
35context.font = "bold 100px Assistant";
36
37context.fillStyle = foregroundColor;
38
39context.textAlign = "center";
40
41context.textBaseline = "middle";
42
43context.fillText(text, canvas.width / 2, canvas.height / 2 );
44
45download.href=canvas.toDataURL("image/png");
46
47return canvas.toDataURL("image/png");
48
49}

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;
2
3canvas.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);
2
3// in our code context.fillrect(0, 0, 200, 200)
4
5context.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";
2
3context.fillStyle = foregroundColor;
4
5context.textAlign = "center";
6
7context.textBaseline = "middle";
8
9// context.fillText( text, x, y);
10
11context.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");
2
3return 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;
2
3var bcgColor= document.getElementById("bcg-color").value;
4
5var 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(" ");
2
3const initials = myNames.shift().charAt(0) + myNames.pop().charAt(0);
4
5const 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");
2
3if (avatarDiv.style.display === "none"){
4
5avatarDiv.style.display = "block";
6
7}
8
9document.getElementById("avatar").src = generateAvatar(
10
11nameInitials,
12
13textColor,
14
15bcgColor
16
17);

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.

Eugene Musebe

Software Developer

I’m a full-stack software developer, content creator, and tech community builder based in Nairobi, Kenya. I am addicted to learning new technologies and loves working with like-minded people.