Word to color

I had to write some code today to convert words into colors, which was a lot of fun. I liked it so such I had to put a working example online.


The code is a simple function. How it works:

  1. We have three channels: red, green, and blue.
  2. Iterate over the word, with the first character adding to red, the second to green, and the third to blue. This continues for the whole word.
  3. Add the Unicode value of the character to a sum. Each time you add a new letter, multiply the value by a multiplier. This multiplier starts at 11 and is multiplied by 11 every time you go through three letters.
  4. Mod each sum by 256 to get the channel value.

    function colorHash(str) {
    var mul = 11;
    var sums = [0, 0, 0];
    var i;
    
    if (str.length === 0) { return [255, 255, 255] }
    
    for (i = 0; i < str.length; i++) {
        sums[i % 3] += (str.charCodeAt(i) * mul);
        if ((i % 3) == 2) {
            mul *= 11;
        }
    }
    
    for (i = 0; i < 3; i++) {
        sums[i] = sums[i] % 256;
    }
    
    return sums;
    }
    
    function toRGBA(sums, alpha) {
    var rgba = "rgba(";
    rgba += sums.map(function (x) { return x.toString() }).join(",")
    rgba += "," + alpha + ")";
    return rgba;
    }