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: 2,166
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.

  1. <div class="inputs">
  2. <form action="">
  3. <label for="firstname">Firstname:</label>
  4. <input type="text" id="firstname" />
  5. <label for="lastname">Lastname:</label>
  6. <input type="text" id="lastname" />
  7. <button type="submit" id="generateAvatar">Generate Image</button>
  8. </form>
  9. </div>
  10. <div class="outputs">
  11. <img id="img" />
  12. </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.

  1. * {
  2. margin: 0;
  3. padding: 0;
  4. box-sizing: border-box;
  5. font-family: Arial, Helvetica, sans-serif;
  6. }
  7. body {
  8. display: flex;
  9. height: 100vh;
  10. width: 100%;
  11. align-items: center;
  12. justify-content: center;
  13. }
  14.  
  15. input[type="text"] {
  16. padding: 0.5rem;
  17. border-radius: 0.3rem;
  18. border: none;
  19. margin: 10px 0;
  20. display: block;
  21. background: #e9e9e9;
  22. }
  23. img {
  24. border: 2px solid #f4f4f4;
  25. border-radius: 50%;
  26. }
  27. .inputs,
  28. .outputs {
  29. padding: 0.5rem 1rem;
  30. }
  31. #generateAvatar {
  32. padding: 0.5rem;
  33. width: 100%;
  34. border-radius: 0.5rem;
  35. border: none;
  36. background-color: #7070ff;
  37. color: #f4f4f4;
  38. cursor:pointer;
  39. }
  40. @media screen and (max-width: 560px) {
  41. body {
  42. flex-direction: column-reverse;
  43. }
  44. }

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.

  1. // selecting components
  2. let firstname, lastname, generate, avatar, ctx, color;
  3. firstname = document.getElementById("firstname");
  4. lastname = document.getElementById("lastname");
  5. generate = document.querySelector("form");
  6.  
  7. //creating canvas
  8. avatar = document.createElement("canvas");
  9. avatar.width = avatar.height = "200";
  10. ctx = avatar.getContext("2d");
  11. ctx.font = `${avatar.width / 2}px Arial`;
  12. ctx.textAlign = "center";
  13.  
  14. //generating color
  15. color = [
  16. "#5050ff",
  17. "#50ff50",
  18. "#ff5050",
  19. "#ff5000",
  20. "#ff0050",
  21. "#0050ff",
  22. "#00ff50",
  23. "#50ff00",
  24. "#5000ff",
  25. ];
  26.  
  27. //functions
  28. //function to get name initials
  29. function getInitials() {
  30. if (lastname.value == "") {
  31. let Initials = firstname.value[0].toUpperCase();
  32. return Initials;
  33. } else {
  34. let Initials = (firstname.value[0] + lastname.value[0]).toUpperCase();
  35. return Initials;
  36. }
  37. }
  38.  
  39. //function to create avatar
  40. function createAvatar(Initials) {
  41. let random = Math.floor(Math.random() * color.length);
  42. //clear canvas
  43. ctx.fillStyle = "#ffffff";
  44. ctx.fillRect(0, 0, avatar.width, avatar.height);
  45.  
  46. //add background
  47. ctx.fillStyle = `${color[random]}60`;
  48. ctx.fillRect(0, 0, avatar.width, avatar.height);
  49.  
  50. //add text
  51. ctx.fillStyle = color[random];
  52. ctx.fillText(Initials, avatar.width / 2, (65 / 100) * avatar.height);
  53.  
  54. //generate as Image
  55. let dataURL = avatar.toDataURL();
  56. document.getElementById("img").src = dataURL;
  57. }
  58. //Event Listener
  59. generate.addEventListener("submit", (e) => {
  60. e.preventDefault();
  61. createAvatar(getInitials());
  62. });
  63.  
  64. // Preloaded avatar for example
  65. 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