How to get name initials as an image?

07 / Dec / 2014 by Sakshi Tyagi 0 comments

While making an application, showing user’s image is a very common use case. Gone were the days when we used to show anonymous image in case a person’s profile image or display image is not present.

We can easily show a person’s name initials as an image to identify the person.

Like :

Screen Shot 2014-12-07 at 13.06.47

Lets consider this html, where we use an angular function defined in the controller, “$scope.getInitials(name)” to get an image in the form of a canvas.


<img ng-src="{{user.profilePicUrl || getInitials(user.name)}}" alt="{{user.name.first}}">

The function “getInitials”:

$scope.getInitials = function (name) {

                var canvas = document.createElement('canvas');
                canvas.style.display = 'none';
                canvas.width = '32';
                canvas.height = '32';
                document.body.appendChild(canvas);
                var context = canvas.getContext('2d');
                context.fillStyle = "#999";
                context.fillRect(0, 0, canvas.width, canvas.height);
                context.font = "16px Arial";
                context.fillStyle = "#ccc";
                var first, last;
                if (name && name.first && name.first != '') {
                    first = name.first[0];
                    last = name.last && name.last != '' ? name.last[0] : null;
                    if (last) {
                        var initials = first + last;
                        context.fillText(initials.toUpperCase(), 3, 23);
                    } else {
                        var initials = first;
                        context.fillText(initials.toUpperCase(), 10, 23);
                    }
                    var data = canvas.toDataURL();
                    document.body.removeChild(canvas);
                    return data;
                } else {
                    return false;
                }
        }

In above function, we dynamically create a canvas and insert it in the document body using “appendChild()” method.

Then, with “getContext()” function we get an object that provides methods and properties for drawing on that canvas. You can have a look at the canvas methods in details here

So, in this way we can get an image using canvas.

Hope this will help :-)

FOUND THIS USEFUL? SHARE IT

Leave a comment -