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.
A hexadecimal color is specified with: #RRGGBB, where the RR (red), GG (green) and BB (blue) hexadecimal integers specify the components of the color.
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.
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.)
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With