Create a random color based on a string using JavaScript
Today we’ll show you how to create a random color based on a string using JavaScript. Here we will create a rgb color based on the first character of a string.
How To Generate a Random Color in JavaScript, get rgb colour based on a string, JavaScript to generate random hex codes of color, string to color javascript, random light color javascript, random material color generator javascript example.
Checkout more articles on JavaScript
Why do we need it?
Sometimes we need to implement a functionality where we have to create an icon based on the user name. That icon contains the background color and first character of a string. Check the below image for your reference.
Function to create a random color
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | function getRandomColor(name) { // get first alphabet in upper case const firstAlphabet = name.charAt(0).toLowerCase(); // get the ASCII code of the character const asciiCode = firstAlphabet.charCodeAt(0); // number that contains 3 times ASCII value of character -- unique for every alphabet const colorNum = asciiCode.toString() + asciiCode.toString() + asciiCode.toString(); var num = Math.round(0xffffff * parseInt(colorNum)); var r = num >> 16 & 255; var g = num >> 8 & 255; var b = num & 255; return { color: 'rgb(' + r + ', ' + g + ', ' + b + ', 0.3)', character: firstAlphabet.toUpperCase() }; } |
Call a function
1 2 3 4 5 | getRandomColor("Clue"); // output: {color: "rgb(240, 189, 193, 0.3)", character: "C"} getRandomColor("Mediator") // output: {color: "rgb(127, 32, 139, 0.3)", character: "M"} |
In the above code, we need to pass the string as a parameter and with the help of the above code we are returning the color in rgb format and the first character of the string in uppercase.
Let’s try to understand the above code
- First we have to get the first alphabet of the given string in upper case.
- Now get the ASCII code of the first character.
- Let’s create a number that contains 3 times ASCII value of character. It’s unique for every alphabet.
- At the last, use
Math.round
to create a rgb code and return it.
That’s it for today.
Thank you for reading. Happy Coding!