🔥 BUILD USER AVATAR GENERATOR IN JAVASCRIPT

Tags: javascript, beginners, html, css
Published: 2021-05-17 10:57:15

In this post we will write a function in javascript to generate beautiful ❤️  user avatar.

First we will add `img` tag to our HTML in which we will render our avatar from javascript.
```html
<img alt="Avatar" id="avatar">
```
Then after that we will write a function `generateAvatar()` in javascript which will return `src` for our `img` tag.This function will take 3 arguments.
1. text - The actual text to show in the avatar image.
2. backgroundColor - The background color of the avatar image.
3. textColor - The color of the text present in the avatar image

Now we will write the actual function to generate the avatar.

Now here firstly we will created new HTML `canvas` element which is used to draw graphics on a web page.Then we will call `getContext()` method on that instance and pass '2d' as argument to it,leading to the creation of a [CanvasRenderingContext2D](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D) object representing a two-dimensional rendering context. 

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

After that with the help of instance of that canvas we will set the `width` and `height` of the canvas.
```js
            canvas.width = 200;
            canvas.height = 200;
```

Then we will draw the background of the `canvas`. First by setting property `fillStyle` on context to backgroundColor we have set the background color of our canvas while by calling function `fillRect()` on context we will draw the actual rectangular shape on our HTML `canvas`.

```js
            // Draw background
            context.fillStyle = backgroundColor;
            context.fillRect(0, 0, canvas.width, canvas.height);
```
here
```js
 context.fillRect(x, y, width, height);
```
- x - The x-axis coordinate of the rectangle's starting point.
- y - The y-axis coordinate of the rectangle's starting point.
- width - The rectangle's width. Positive values are to the right, and negative to the left.
- height - The rectangle's height. Positive values are down, and negative are up.

Now after that we will draw text on the `canvas`
```js
   // Draw text
    context.font = "bold 100px Assistant";
    context.fillStyle = textColor;
    context.textAlign = "center";
    context.textBaseline = "middle";
    context.fillText(text, canvas.width / 2, canvas.height / 2);
```
Now this will create the `canvas` with background and text in it.But we have to render this into `img` tag. So we will call `toDataURL()`method on `canvas` which will return a data URI containing a representation of the image in the format specified by the type parameter (defaults to PNG).

And the completed function will look like below

```html
<script>
        function generateAvatar(
            text,
            foregroundColor = "white",
            backgroundColor = "black",
            size=250
        ) {
            const canvas = document.createElement("canvas");
            const context = canvas.getContext("2d");

            canvas.width = 200;
            canvas.height = 200;

            // Draw background
            context.fillStyle = backgroundColor;
            context.fillRect(0, 0, canvas.width, canvas.height);

            // Draw text
            context.font = "bold 100px Assistant";
            context.fillStyle = foregroundColor;
            context.textAlign = "center";
            context.textBaseline = "middle";
            context.fillText(text, canvas.width / 2, canvas.height / 2);

            return canvas.toDataURL("image/png");
        }

    </script>
```
Now we will use this to render avatar in our `img` tag as below
```js
document.getElementById("avatar").src = generateAvatar(
            "SN",
            "white",
            "#ff3399"
        );
```
This will create the following result in browser - 
![avatar-1.png](https://res.cloudinary.com/dh1srz69c/image/upload/v1621248198/avatar_1_7b453acc30.png)


Now to make it circular we will add CSS `border-radius` property of the `img` to `50%` as below
```html
    <style>
        #avatar {
            border-radius: 50%;
        }
    </style>
```
Which will generate following result in browser. - 
![avatar-2.png](https://res.cloudinary.com/dh1srz69c/image/upload/v1621248222/avatar_2_cb80078801.png)

Hope this will help you 😇. Thanks for reading. You can visit my [Personal Blog](https://satishnaikawadi.me/posts) for more tutorials like this.