Show avatar display name (default) in Canvas if image is unavailable

Is there a way to show an avatar by using the first letters of a name, similar to what Google does when the actual image is not available? https://i.sstatic.net/EMozW.png ========> https://i.sstatic.net/WfWN2.png

I am looking for a solution that involves generating a fallback image using canvas.

Answer №1

Utilizing only HTML and CSS, there are various methods to identify the image element.

.avatar{
    background: #D770AD;
    padding: 10px;
    width: 32px;
    height: 32px;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    -ms-border-radius: 50%;
    border-radius: 50%;
    display: inline-block;
    text-align: center;
    line-height: 32px;
    font-weight: 700;
    margin-right: 5px;
    color: #FFFFFF;
  }
<div class="avatar">FL</div>

Answer №2

I have come up with a solution, but I believe there is room for improvement. Let's take a look at it: Creating a backup canvas using the provided name

  var username = attr.username;
  var name = attr.name;
  var imgSrc = "https://path/to/server/"+username+".jpg";


  var canvas = document.createElement('canvas'); //es-lint disable
  canvas.width = '32';
  canvas.height = '32';
  var context = canvas.getContext('2d');
  context.fillStyle = "#D6B478";
  context.fillRect(0, 0, canvas.width, canvas.height);
  context.font = "16px 'Roboto'";
  context.fillStyle = "white";
  var nameArr = name.split(' ')
  context.fillText(nameArr[0].charAt(0)+nameArr[1].charAt(0),7,22
  var dataUrl = canvas.toDataURL();

Managing image loading and error handling

  var elem = document.getElementById('#Target')
  var img = new Image();
  img.src = imgSrc;
  elem.html('<img src="'+dataUrl+'" alt="" />')
  img.onerror = function () {
    console.log("An error occurred while loading the Avatar for " + imgSrc);
    img.onerror = null
    img.src = dataUrl
  }
  img.onload = function () {
    elem.html('')
    elem.append(img)
  }

Answer №3

Here is the code snippet for generating an image using JavaScript

var colors = ["#1abc9c", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#2c3e50", "#f1c40f", "#e67e22", "#e74c3c", "#95a5a6", "#f39c12", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"];

    var name = "John Doe",
      nameSplit = name.split(" "),
      initials = nameSplit[0].charAt(0).toUpperCase() + nameSplit[1].charAt(0).toUpperCase();

    var charIndex = initials.charCodeAt(0) - 65,
      colorIndex = charIndex % 19;

    var canvas = document.createElement('canvas'); 
    canvas.width = '32';
    canvas.height = '32';
    var context = canvas.getContext("2d");
    context.fillStyle = colors[colorIndex];
    context.fillRect (0, 0, canvas.width, canvas.height);
    context.font = "16px Arial";
    context.textAlign = "center";
    context.fillStyle = "#FFF";
    context.fillText(initials,16,22);
    var dataUrl = canvas.toDataURL();
    return dataUrl;       

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The side column does not reach the full height

I'm currently working on a sidebar for my website and I'm attempting to make it fill the remaining height of the page after the elements above it. Unfortunately, I haven't been successful in figuring out how to achieve this. I am utilizing B ...

Another option instead of using the .siblings() method would be

Is there an alternative to using the .siblings() method in jQuery for traversing through divs of a specific class in separate container divs? How can this be achieved with the following code: HTML: <div id="container1"> <div id="1"></di ...

Placing the date of each blog post at the end of the excerpt

Currently, there is a grid section on the homepage of our site showcasing the two most recent blog posts. I am looking for a Javascript solution to relocate the date to the bottom of each block, outside of the border. For reference, you can visit the follo ...

When using HTML/Bootstrap5, the ms-auto class does not correctly align items to the right in the navbar

I'm currently working on mastering bootstrap through an online tutorial, but I've hit a roadblock when it comes to right-aligning items in a navbar. I've double-checked my code against the instructor's, and it's a perfect match: &l ...

Switching the arrow direction in Bootstrap 4 menu toggles

I'm a beginner with Bootstrap 4. My navigation menu includes a dropdown item with the standard caret pointing down, added automatically by Bootstrap. Now, I want to make the caret point up after opening the dropdown menu for the nav item. Despite ext ...

Is there a way to load textures or images beforehand in Three.js so that we won't have to wait during the

Currently, I'm working on a project that involves showcasing texture changes of an object over a period of time using a timeline. When the user interacts by clicking on a specific point, new values such as size, texture, and color are loaded onto the ...

Is it acceptable to conceal items by utilizing display:none?

When dealing with a dynamic website that includes components from various plugins, is it acceptable to hide elements temporarily or permanently using display:none? Sometimes clients may request certain items to be hidden from the page, so instead of removi ...

Padding on hover for navigation bar dropdowns

Having issues with a drop-down navigation menu that works fine except for the "videos" item. The hover color change doesn't cover the entire width due to padding settings. Struggling to fix this without affecting the "photography" item. Need help figu ...

Count the number of documents in a MongoDB aggregation cursor

After exploring the API documentation, I noticed that cursor.count() function is no longer available. This led me to wonder if there was an alternative way to obtain a count of the aggregate data. My goal is to determine the total number of documents whi ...

Is there a way to customize padding and color in HTML table cells?

I am looking to style cell d with a full yellow background in my HTML code for Outlook display. How can I achieve this? To clarify, I am using agility HTML pack to make changes to the cell d at runtime while ensuring that the table remains well-formatted. ...

Implementing a Comment Section on Your Website with HTML and JavaScript

Currently in the process of setting up my static webpage, and looking to incorporate user comments. I have already written the comment script using HTML, but I am unsure how to write the JavaScript necessary to display the comments beneath each post. Any ...

Error encountered while executing node server.js for Azure IoT Hub due to incorrect flags provided in the RegExp constructor

Currently, I am attempting to execute 'node server.js' in order to establish a connection between my Raspberry Pi device and Azure through the Azure IoT Hub. However, upon running the command 'node server.js', an error message is displa ...

Difficulty being faced in recognizing anchor tags through CSS selector methods by Mechanize

(Just wanted to check here since I didn't get much response on RailsForum lately.) Has anyone encountered issues with Mechanize not picking up anchor tags using CSS selectors? Here's a snippet of the HTML code: <td class='calendarCell& ...

Guide for controlling inline SVG with vuex

Currently, I am working on a customizing tool for cursors using Vuejs and Vuex. My main challenge lies in the process of binding the color selected by the user to the fill property of an SVG cursor. Allow me to explain step by step how everything is suppos ...

Achieving a full-height accordion with each pane taking up the entirety of the viewport using Bootstrap 4

https://i.sstatic.net/LqhXn.png I found this image which perfectly explains what I'm trying to achieve. This is my current code: <div class="accordion" id="myAccordion"> <div class="card"> ...

When a new ajax function is added, the original Ajax code stops functioning

I've been working on getting the code below to function properly. It seems that when I test the code, two validation functions are working correctly. However, when I include the validateUsername() function along with the if statement in the code, ever ...

"I am having trouble with req.body in my Express JavaScript application as it is not returning the data from POST requests. Can

Being new to building an express server in NodeJS, I've been able to work on POSTs and GETs using routes and controllers. However, I'm puzzled as to why req.body is showing {} in the terminal. It seems like no data is being received from AJAX. Ca ...

Transferring data via ajax from the View to ActionResult action method

Issue with data delivery from view to controller using AJAX in ASP.NET MVC project Description of the problem: function submit() { var obj = {}; obj.PD = getResult('pd'); obj.MD = getResult('md'); obj.C = getResult(&a ...

Connecting Ionic/Angular directives to scrollbars

I'm having an issue with my scrolling div: <div class="list"> <div class="item" ng-repeat="post in posts"> <img src="post.img" is-visible/> </div> </div> and I've implemented this directive: angular.elemen ...

Utilizing TypeScript to leverage JavaScript, employing webpack for bundling, and encountering runtime errors

I have a simple JavaScript function that compares alphanumeric values: function alphanum(a, b) { function chunkify(t) { var tz = [], x = 0, y = -1, n = 0, i, j; while (i = (j = t.charAt(x++)).charCodeAt(0)) { var m = (i == 46 || (i >=4 ...