Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a hexadecimal colour based on a string with JavaScript

I want to create a function that will accept any old string (will usually be a single word) and from that somehow generate a hexadecimal value between #000000 and #FFFFFF, so I can use it as a colour for a HTML element.

Maybe even a shorthand hex value (e.g: #FFF) if that's less complicated. In fact, a colour from a 'web-safe' palette would be ideal.

like image 224
Darragh Enright Avatar asked Aug 06 '10 17:08

Darragh Enright


People also ask

How do you color a hexadecimal in HTML?

A hexadecimal color is specified with: #RRGGBB, where the RR (red), GG (green) and BB (blue) hexadecimal integers specify the components of the color.

Can hexadecimal represent colors?

A color hex code is a hexadecimal way to represent a color in RGB format by combining three values – the amounts of red, green and blue in a particular shade of color. These color hex codes have been an integral part of HTML for web design, and remain a key way of representing color formats digitally.


2 Answers

Here's an adaptation of CD Sanchez' answer that consistently returns a 6-digit colour code:

var stringToColour = function(str) {   var hash = 0;   for (var i = 0; i < str.length; i++) {     hash = str.charCodeAt(i) + ((hash << 5) - hash);   }   var colour = '#';   for (var i = 0; i < 3; i++) {     var value = (hash >> (i * 8)) & 0xFF;     colour += ('00' + value.toString(16)).substr(-2);   }   return colour; } 

Usage:

stringToColour("greenish"); // -> #9bc63b 

Example:

http://jsfiddle.net/sUK45/

(An alternative/simpler solution might involve returning an 'rgb(...)'-style colour code.)

like image 183
Joe Freeman Avatar answered Sep 23 '22 02:09

Joe Freeman


Just porting over the Java from Compute hex color code for an arbitrary string to Javascript:

function hashCode(str) { // java String#hashCode     var hash = 0;     for (var i = 0; i < str.length; i++) {        hash = str.charCodeAt(i) + ((hash << 5) - hash);     }     return hash; }   function intToRGB(i){     var c = (i & 0x00FFFFFF)         .toString(16)         .toUpperCase();      return "00000".substring(0, 6 - c.length) + c; } 

To convert you would do:

intToRGB(hashCode(your_string)) 
like image 26
Cristian Sanchez Avatar answered Sep 22 '22 02:09

Cristian Sanchez