Generate Avatars with Initials From Name in JavaScript

Generate Avatars with Initials From Name in JavaScript
Code Snippet:Name Initial Avatar
Author: Karan Gaba
Published: January 14, 2024
Last Updated: January 22, 2024
Downloads: 1,586
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code helps you to generate avatars with initials from the name. It works by taking your first and last name as input and generating a unique avatar based on the initials. This code is helpful for creating custom avatars for users on websites or applications.

You can use this code in user profile sections of websites and apps to provide personalized avatars. Plus, it simplifies the process of creating avatars with initials, saving development time.

How to Generate Avatars with Initials From Name In JavaScript

1. First, create the HTML structure as follows. This code sets up a simple form for entering the first and last names and an empty img tag for displaying the generated avatar.

 <div class="inputs">
      <form action="">
        <label for="firstname">Firstname:</label>
        <input type="text" id="firstname" />
        <label for="lastname">Lastname:</label>
        <input type="text" id="lastname" />
        <button type="submit" id="generateAvatar">Generate Image</button>
      </form>
    </div>
    <div class="outputs">
      <img id="img" />
    </div>

2. Apply CSS styles to make your form and avatar look attractive. This is an example of some basic styling, but you can customize it to your liking.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: Arial, Helvetica, sans-serif;
}
body {
  display: flex;
  height: 100vh;
  width: 100%;
  align-items: center;
  justify-content: center;
}

input[type="text"] {
  padding: 0.5rem;
  border-radius: 0.3rem;
  border: none;
  margin: 10px 0;
  display: block;
  background: #e9e9e9;
}
img {
  border: 2px solid #f4f4f4;
  border-radius: 50%;
}
.inputs,
.outputs {
  padding: 0.5rem 1rem;
}
#generateAvatar {
  padding: 0.5rem;
  width: 100%;
  border-radius: 0.5rem;
  border: none;
  background-color: #7070ff;
  color: #f4f4f4;
  cursor:pointer;
}
@media screen and (max-width: 560px) {
  body {
    flex-direction: column-reverse;
  }
}

3. Finally, let’s add the JavaScript code to your project. This code will handle user input, generate the avatar, and display it on the page.

// selecting components
let firstname, lastname, generate, avatar, ctx, color;
firstname = document.getElementById("firstname");
lastname = document.getElementById("lastname");
generate = document.querySelector("form");

//creating canvas
avatar = document.createElement("canvas");
avatar.width = avatar.height = "200";
ctx = avatar.getContext("2d");
ctx.font = `${avatar.width / 2}px Arial`;
ctx.textAlign = "center";

//generating color
color = [
  "#5050ff",
  "#50ff50",
  "#ff5050",
  "#ff5000",
  "#ff0050",
  "#0050ff",
  "#00ff50",
  "#50ff00",
  "#5000ff",
];

//functions
//function to get name initials
function getInitials() {
  if (lastname.value == "") {
    let Initials = firstname.value[0].toUpperCase();
    return Initials;
  } else {
    let Initials = (firstname.value[0] + lastname.value[0]).toUpperCase();
    return Initials;
  }
}

//function to create avatar
function createAvatar(Initials) {
  let random = Math.floor(Math.random() * color.length);
  //clear canvas
  ctx.fillStyle = "#ffffff";
  ctx.fillRect(0, 0, avatar.width, avatar.height);

  //add background
  ctx.fillStyle = `${color[random]}60`;
  ctx.fillRect(0, 0, avatar.width, avatar.height);

  //add text
  ctx.fillStyle = color[random];
  ctx.fillText(Initials, avatar.width / 2, (65 / 100) * avatar.height);

  //generate as Image
  let dataURL = avatar.toDataURL();
  document.getElementById("img").src = dataURL;
}
//Event Listener
generate.addEventListener("submit", (e) => {
  e.preventDefault();
  createAvatar(getInitials());
});

// Preloaded avatar for example
createAvatar("KG");

That’s all! You’ve successfully implemented an avatar generator using JavaScript. You can further enhance and customize this code to suit your specific project requirements. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X