Create a hexadecimal colour based on a string with JavaScript

后端 未结 13 915
旧时难觅i
旧时难觅i 2020-11-30 17:15

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

13条回答
  •  自闭症患者
    2020-11-30 18:03

    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.)

提交回复
热议问题