DEV Community

Cover image for Build a User Profile Avatar Generator with JavaScript πŸ§‘πŸ‘©β€πŸ’»
Dom (dcode)
Dom (dcode)

Posted on

Build a User Profile Avatar Generator with JavaScript πŸ§‘πŸ‘©β€πŸ’»

Let's take a look at how to generate user avatars for the web using some client-side JavaScript. The tools for the job include HTML5 canvas and data URLs πŸ™‚

This will reduce the amount of requests you have to the server side and as a result speed up your load times ⚑

Video Tutorial

As usual with my posts, if you prefer to watch a video tutorial of this, give it a watch on my YouTube channel, dcode:

Source Code

If you prefer to follow a long with code, here it is:

Writing the HTML

For the HTML, we only need a single image tag which will (eventually) hold the avatar.

<img id="avatar" alt="Avatar">
Enter fullscreen mode Exit fullscreen mode

And the JavaScript...

This will work on a single function which takes in a couple of options including the text to display, a foreground color and background color.

function generateAvatar(text, foregroundColor, backgroundColor) {
    const canvas = document.createElement("canvas");
    const context = canvas.getContext("2d");

    canvas.width = 200;
    canvas.height = 200;

    // Draw background
    context.fillStyle = backgroundColor;
    context.fillRect(0, 0, canvas.width, canvas.height);

    // Draw text
    context.font = "bold 100px Assistant";
    context.fillStyle = foregroundColor;
    context.textAlign = "center";
    context.textBaseline = "middle";
    context.fillText(text, canvas.width / 2, canvas.height / 2);

    return canvas.toDataURL("image/png");
}
Enter fullscreen mode Exit fullscreen mode

In the first chunk of code we're doing standard procedure for canvases, creating a new canvas to work on and getting the 2D context to draw.

Next we set the width and height to the same value.

After this we draw the background by firstly setting the active fill color on the context, followed by a full-width rectangle to represent the background.

Next up is the text, and for this one we simply set the font family as well as instruct the text to be in the center, vertically and horizontally. It's then drawn on the canvas using fillText.

And lastly, we return a data URL of a PNG image for the canvas itself. We can then place the data URL in the src attribute of our <img> tag once calling the function:

document.getElementById("avatar").src = generateAvatar("SP", "white", "#009578");
Enter fullscreen mode Exit fullscreen mode

And here's what we get:
Avatar Image Example

Easy done. You can now generate avatar images on the client-side 😎

Discussion (5)

Collapse
yogeshktm profile image
yogeshwaran

Interesting use case :)

But i would go for simpler CSS solution without java script and images.

if there is no avatar images server side code will have to return first characters of first name and last name. we can simply style it.

Collapse
fauziferdiansyah profile image
Fauzi Ferdiansyah • Edited on

JS one line =

let name = "Fauzi Ferdiansyah Dacil #$*(&#";
name.match(/(\b\S)?/g).join("")
    .match(/(^\S|\S$)?/g)
    .join("").toUpperCase();
// return will "FD"
Enter fullscreen mode Exit fullscreen mode
Collapse
iamtomiwa profile image
Ajayi Emmanuel Tomiwa

This will come in handy. Thanks a lot

Collapse
g0tie profile image
g0tie

Fun to do, here my version: codepen.io/g0tie_js/full/MWjNMrW

Collapse
arberbr profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
Arber Braja

Why? Simply, why? Why JS?

From what I see that is a very simple element. One of the simplest of alll.

A circle with initials shown centered.

What's the need here to use JS? Just because you can? Well just because you can you could have built 3-4 microservices to talk with each other just to spit out a circle with 2 initials ... but it does not change the fact that its still a circle with 2 initials.