Create a hexadecimal colour based on a string with JavaScript

后端 未结 13 918
旧时难觅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:12

    Using the hashCode as in Cristian Sanchez's answer with hsl and modern javascript, you can create a color picker with good contrast like this:

    function hashCode(str) {
      let hash = 0;
      for (var i = 0; i < str.length; i++) {
        hash = str.charCodeAt(i) + ((hash << 5) - hash);
      }
      return hash;
    }
    
    function pickColor(str) {
      return `hsl(${hashCode(str) % 360}, 100%, 80%)`;
    }
    
    one.style.backgroundColor = pickColor(one.innerText)
    two.style.backgroundColor = pickColor(two.innerText)
    div {
      padding: 10px;
    }
    One
    Two

    Since it's hsl, you can scale luminance to get the contrast you're looking for.

    function hashCode(str) {
      let hash = 0;
      for (var i = 0; i < str.length; i++) {
        hash = str.charCodeAt(i) + ((hash << 5) - hash);
      }
      return hash;
    }
    
    function pickColor(str) {
      // Note the last value here is now 50% instead of 80%
      return `hsl(${hashCode(str) % 360}, 100%, 50%)`;
    }
    
    one.style.backgroundColor = pickColor(one.innerText)
    two.style.backgroundColor = pickColor(two.innerText)
    div {
      color: white;
      padding: 10px;
    }
    One
    Two

提交回复
热议问题