Compute an arbitrary color for user avatar starting from their username (with Javascript).

Sergio Pedercini
2 min readNov 21, 2017

Working on a javascript web application, it happened they asked me to assign to each user Avatar a background color, to identify the user in case they hadn’t upload a custom profile picture. Another request was to use only pastel tones, to avoid conflicts with the main colors of the UI.

How to get a permanent color for each user, if I don’t know anything but their name? Simple: I’m using the name to generate the color!

Uh! The color computed for my name is a beautiful pastel green!

Here what we need to do

  1. generate the Avatar background color starting from the user name;
  2. use the HSL format to select only pastel tones.

The javascript function

The function returns the color in HSL format hsl(hue, saturation, lightness) and accept three parameters:

  1. a string (str): we will use it to get the hue parameter of the returned color;
  2. the saturation (s) of returned color: a number between 0 and 100;
  3. the lightness (l) of returned color: a number between 0 and 100.
strToHslColor('Sergio Pedercini', 30, 80);// => hsl(98, 30%, 80%)
// It's a pastel green!

How it works

We can split this function in two separate moments:

In the first, the function converts the given string (the user name) to a numeric hash getting the Unicode value from each character in the string (rows 2 → 5).

var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}

In the second, it converts the returned hash to a number between 0 and 360 with modulus javascript function (row 7).

var h = hash % 360;

Now we can use the other two parameters, saturation and lightness, to limit the color spectrum only to pastel tones. Two good candidates are respectively 30 and 80.

Here a live example

Open this example in CodePen.

If you like this post please give it some claps and follow me to stay tuned for more stories and tutorials.

And don’t forget to take a look at my Twitter profile!

--

--