Create a Letter Picture Like Google Does With React
Add a nice default image for users without profile pictures
Imagine that your next request is to perform this function: If the user does not have a profile image, the system must take their name and create an image from their initials in the purest Google style.
You say it is possible, but you still have no idea how. And so you ended up here…
What Is a Letter Picture?

When a Google service cannot find a photo of your profile, it will take your initials and create a small representative image of your profile. It’s a very pleasant practice for the user experience.
Let’s Start

We will work on the app component. We will create a component called utilities
that will contain all the functions that we will need to create the image.
Our app will be quite simple in that we will export the two functions that we will need. An image where your src
is will have a conditional. If the src
field is empty, we will call our function to generate an image with the initials. Otherwise, the src
will be the image that we bring from the database.
Our function will receive three parameters: image size, username, and color.
To make it more personalized in the last value, we will send a function that will generate a random color each time the page is reloaded.
You can ignore this function and pass a hex color.
We will start working on the utils
file. First, we will create the function to generate colors randomly:
Now we will see in detail our function to take the initials of the username:
If our name is empty, we return immediately since we will not be able to do anything. Otherwise, we transform the string into an array with split
.
As W3Schools notes, “The split()
method is used to split a string into an array.”

Once we have this array, we will know that the first name is in position [0]
and the last name is in position [1]
. We proceed to use subString
.
According to W3Schools, “The substring()
method extracts the characters from a string, between two specified indices.” In this case, since we only want to use the first letter, our indices will be 0
and 1
. Finally, we concatenate that result and return the new string:
Here is the function to create our image:

The canvas
element has no drawing abilities of its own. It is just a container for graphics.
As written in JavaScript and jQuery Made Easy, the getContext()
method “returns an object that provides methods and properties for drawing on the canvas.”
canvas.width=canvas.height
is used to create a square for the canvas.

The fillRect()
method draws a “filled” rectangle. With the size we’re passing, we fill a square.

Finally, we will manage the text
property so that our initials are at the center of the square. Remember to specify a font. Otherwise, the default text will appear small, ignoring the size.
Our final result would be this:

Complete code:
I hope this tutorial was useful. Thanks for reading!
