In cases you want to display a more personalized avatar for a user that hasn’t uploaded any image to his profile, Canvas might help you through its toDataURI() function. So, let’s see what this method is all about.

The HTMLCanvasElement.toDataURL() method returns a data URIs containing a representation of the image in the format specified by the type parameter (defaults to PNG). The returned image is in a resolution of 96 dpi.

  • If the height or width of the canvas is 0, the string "data:," is returned.
  • If the requested type is not image/png, but the returned value starts with data:image/png, then the requested type is not supported.
  • Chrome also supports the image/webp type.

More info can be found on the MDN site.

Knowing that we can write a simple javascript function that takes some letters as parameters, we can generate a representation of the image as base64 encoding.

/**
 * Generate an avatar image from letters
 */
(function (w, d) {

  function AvatarImage(letters, size) {
    var canvas = d.createElement('canvas');
    var context = canvas.getContext("2d");
    var size = size || 60;

    // Generate a random color every time function is called
    var color =  "#" + (Math.random() * 0xFFFFFF << 0).toString(16);

    // Set canvas with & height
    canvas.width = size;
    canvas.height = size;

    // Select a font family to support different language characters
    // like Arial
    context.font = Math.round(canvas.width / 2) + "px Arial";
    context.textAlign = "center";

    // Setup background and front color
    context.fillStyle = color;
    context.fillRect(0, 0, canvas.width, canvas.height);
    context.fillStyle = "#FFF";
    context.fillText(letters, size / 2, size / 1.5);

    // Set image representation in default format (png)
    dataURI = canvas.toDataURL();

    // Dispose canvas element
    canvas = null;

    return dataURI;
  }

  w.AvatarImage = AvatarImage;

})(window, document);

Then, when the page loads, we shall transform all images with an extra “letter” parameter like this one:

<img width=”60″ height=”60″ letters=”PP” /> 

to image

(function(w, d) {

  function generateAvatars() {
    var images = d.querySelectorAll('img[letters]');

    for (var i = 0, len = images.length; i < len; i++) {
      var img = images[i];
      img.src = AvatarImage(img.getAttribute('letters'), img.getAttribute('width'));
      img.removeAttribute('letters');
    }
  }

  d.addEventListener('DOMContentLoaded', function (event) {
      generateAvatars();
  });

})(window, document);

 

 

Categorized in:

Tagged in: