How to create user avatar generator jQuery Plugin?

In this article, we are going to build an avatar generator jQuery plugin using html5 canvas and jQuery from scratch. This is very easy to achieve and the main benefit of doing this is going to reduce our network traffic. For example, instead of generating our avatars on the server-side, we can do it on the client-side instead.

So this will be going to save our requests to the server and also speed up our application or our web page. So let’s build the plugin step by step.

How to create user avatar generator jQuery Plugin?

Step 1: Write basic jQuery plugin.

As we are going to create this plugin using jQuery, first check the basic jQuery plugin structure. But in this tutorial, we are not going to cover all plugin related code. I hope you have a basic idea about the jQuery plugin. You can also check their official documents here. Ok, so let’s check the basic plugin structure.

(function ( $ ) {
	$.fn.yourPluginName = function( options ) {
		// do what ever you want
		return this;
	};
}( jQuery ));

$("element").yourPluginName();

In the above example, yourPluginName is your plugin name. In this case, we will use makeAvatar as our plugin name.

Step 2: Define Plugin options.

The plug-in that we are going to create needs some default options. For example, let’s say the height and width of the avatar, the background and foreground color, avatar text etc. So let’s see how we set those options.

(function ( $ ) {
	$.fn.makeAvatar = function( options ) {
		
		//default options
		const settings = $.extend({
			default_text: "AB",
			height: 200,
			width: 200,
			textcolor: "#fff",
			backcolor: "#000",
			fontsize: 100,
			image_circle: false
		}, options );
		return this;
	};
}( jQuery ));

There are many options here, so let’s see what these options will do.

default_textIf no text is specified then the default text “AB” will show.
heightHeight of the avatar. The default value we have set 200px.
widthWidth of the avatar. The default value we have set 200px.
textcolorThe foreground color of the avatar. The default value is white.
backcolorThe background color of the avatar. The default value is black.
fontsizeFont size. Default font size 100px.
image_circleIf we want the avatar circle in shape. The default value is false.

In the above example, we have taken an object constant i.e. settings. Here we have merged two objects i.e. options supplied by the jQuery plugin and the default options that we have discussed earlier through JQuery extend().

Step 2: Create canvas.

Now we will take two constants, one is canvas and the other is context. So lets check the code.

const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");

canvas.width = settings.height.toString().replace(/\D/g,'');
canvas.height = settings.width.toString().replace(/\D/g,'');

//text
context.font = "bold "+ settings.fontsize.toString().replace(/\D/g,'') +"px Assistant";
context.textAlign = "center";
context.textBaseline = "middle";

In the above example, we have created a canvas element and store it’s 2d context in context constant by using getContext() function. After that we have set the canvas height and width from our plugin’s default value. So we from the settings object, we get the height and width value.

In this case, we need some checking. That means a user may pass the height and width value with “px” or without “px”. So we need only numeric value. To do that we have converted it to string and in replace() function, we used regex i.e replace(/\D/g,”). It will strip a non-neumaric value from a string.

In font option, we have set font weight to “bold” and here we are going to use the font called “Assistant”. Now the text align we have set here “center” that will make the text horizontally center. The text baseline property is going to vertically center. So to do that, we have to use the value “middle”.

Step 3: Draw the image on canvas.

Lets look into the code first. After that we are going to check each line to understand it properly.

this.filter( "img" ).each(function() {
	const img = $( this );

	//background
	context.fillStyle = img.data('background') ? img.data('background') : settings.backcolor;
	context.fillRect(0, 0, canvas.width, canvas.height);
	
	//text color
	context.fillStyle = settings.textcolor;
	context.fillText(img.data('avatar') ? img.data('avatar') : settings.default_text, canvas.width / 2, canvas.height / 2);
	
	img.attr("src", canvas.toDataURL("image/png"));
	context.clearRect(0, 0, canvas.width, canvas.height);
});

Here the term “this” will indicate the DOM elements. So by using the jQuery filter() function, we only take img elements. Let’s suppose we have multiple image elements with the same class called “avatar”. If we called our plugin like $(".avatar").makeAvatar(); , the filter() function will get all image elements which class name is “avatar”.

Each () function will loop through all image elements. Here we stored the image element into img constant. If you want to know what is const and let, then read my article Let vs const in JavaScript .

Ok so think about a situation, we need to change the back color of a user avatar. But how to do that? Well, we are going to use data-attribute here. That means we can override the back color of a particular image avatar by using data-background attribute.

So in fillstyle we are going to check if the user wants to override the back color. If not then use the default back color.

context.fillStyle = img.data('background') ? img.data('background') : settings.backcolor;

Next, we will fill the background with the background color by using fillrect. The first two parameters are the x and y coordinate and the other two parameters are the height and width of the canvas.

Same code for the text style also. But in this case, we are going to use data-avatar as data-attribute to draw the text on canvas. If we don’t pass anything from the data-attribute or from plugin default_text, or it will show the default value i.e “AB”.

In filltext() the last two parameters are x and y coordinate. Here we divided canvas height and width by 2. It is because it will make the text horizontally and vertically center.

Now we are going to convert to dataurl by using toDataURL() function and set the value as src attribute of that image. To use this canvas for next image element, we need to clear it first. otherwise previous text will be shown on next image.

Step 4: Set rounded avatar.

Sometimes we need rounded image. So to do that, we have use img_circle option. By default it is false. But if need rounded image, then we have to check if img_circle is true or not. If true then set the image border-radius to 50%.

if(settings.image_circle){
    this.css( "border-radius", "50%" );
}

So here is our complete code. Copy the code below and save it to makeAvatar.js

(function ( $ ) {
	$.fn.makeAvatar = function( options ) {
		
		const settings = $.extend({
			default_text: "AB",
			height: 200,
			width: 200,
			textcolor: "#fff",
			backcolor: "#000",
			fontsize: 100,
			img_circle: false
		}, options );
		

		const canvas = document.createElement("canvas");
		const context = canvas.getContext("2d");

		canvas.width = settings.height.toString().replace(/\D/g,'');
		canvas.height = settings.width.toString().replace(/\D/g,'');

		//text
		context.font = "bold "+ settings.fontsize.toString().replace(/\D/g,'') +"px Assistant";
		context.textAlign = "center";
		context.textBaseline = "middle";
		


		this.filter( "img" ).each(function() {
			const img = $( this );

			//background
			context.fillStyle = img.data('background') ? img.data('background') : settings.backcolor;
			context.fillRect(0, 0, canvas.width, canvas.height);
			
			//text color
			context.fillStyle = settings.textcolor;
			context.fillText(img.data('avatar') ? img.data('avatar') : settings.default_text, canvas.width / 2, canvas.height / 2);
			
			img.attr("src", canvas.toDataURL("image/png"));
			context.clearRect(0, 0, canvas.width, canvas.height);
		});
		
		if(settings.image_circle){
			this.css( "border-radius", "50%" );
		}
		
		return this;
 
	};
 
}( jQuery ));

How to use this plugin?

First add makeAvatar.js into your documents after jQuery plugin. Follow the steps to use it in your application.

<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Make Avatar jquery plugin</title>
	</head>

	<body>
		<img class="avatar" />
		<img class="avatar" />
		<img class="avatar" />
		

		<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
		<script src="makeAvatar.js"></script>
		<script>
			$(document).ready(function(){
                                //basic initialization
				$(".avatar").makeAvatar();
			});
		</script>
	</body>
</html>
<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Make Avatar jquery plugin</title>
	</head>

	<body>
		<img class="avatar" />
		<img class="avatar" data-background="#12558d"/>
		<img class="avatar" data-avatar="XY" />
		

		<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
		<script src="makeAvatar.js"></script>
		<script>
			$(document).ready(function(){
                                $(".avatar").makeAvatar({
					default_text: "CB",
					backcolor: "#f26522"
				});
			});
		</script>
	</body>
</html>

So next example we will check how to make rounded image and how to decrease height and width?

<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Make Avatar jquery plugin</title>
	</head>

	<body>
		<img class="avatar" />
		<img class="avatar" data-background="#12558d"/>
		<img class="avatar" data-avatar="XY" />
		

		<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
		<script src="makeAvatar.js"></script>
		<script>
			$(document).ready(function(){
                               $(".avatar").makeAvatar({
					default_text: "CB",
					backcolor: "#f26522",
					height: 100,
					width: 100,
					fontsize: 50,
					image_circle: true
				});
			});
		</script>
	</body>
</html>

So that’s all. This is a basic jQuery plugin. You can also include advanced feature. Thanks for reading this article, guys and will see you in the next session.

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Leave a Comment