Create a hexadecimal colour based on a string with JavaScript

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

    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))
    
    0 讨论(0)
  • 2020-11-30 18:09

    I convert this for Java.

    Tanks for all.

    public static int getColorFromText(String text)
        {
            if(text == null || text.length() < 1)
                return Color.BLACK;
    
            int hash = 0;
    
            for (int i = 0; i < text.length(); i++)
            {
                hash = text.charAt(i) + ((hash << 5) - hash);
            }
    
            int c = (hash & 0x00FFFFFF);
            c = c - 16777216;
    
            return c;
        }
    
    0 讨论(0)
  • 2020-11-30 18:10

    All you really need is a good hash function. On node, I just use

    const crypto = require('crypto');
    function strToColor(str) {
        return '#' + crypto.createHash('md5').update(str).digest('hex').substr(0, 6);
    }
    
    0 讨论(0)
  • 2020-11-30 18:12

    I have opened a pull request to Please.js that allows generating a color from a hash.

    You can map the string to a color like so:

    const color = Please.make_color({
        from_hash: "any string goes here"
    });
    

    For example, "any string goes here" will return as "#47291b"
    and "another!" returns as "#1f0c3d"

    0 讨论(0)
  • 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;
    }
    <div id="one">One</div>
    <div id="two">Two</div>

    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;
    }
    <div id="one">One</div>
    <div id="two">Two</div>

    0 讨论(0)
  • 2020-11-30 18:15

    This function does the trick. It's an adaptation of this, fairly longer implementation this repo ..

    const color = (str) => {
        let rgb = [];
        // Changing non-hexadecimal characters to 0
        str = [...str].map(c => (/[0-9A-Fa-f]/g.test(c)) ? c : 0).join('');
        // Padding string with zeroes until it adds up to 3
        while (str.length % 3) str += '0';
    
        // Dividing string into 3 equally large arrays
        for (i = 0; i < str.length; i += str.length / 3)
            rgb.push(str.slice(i, i + str.length / 3));
    
        // Formatting a hex color from the first two letters of each portion
        return `#${rgb.map(string => string.slice(0, 2)).join('')}`;
    }
    
    0 讨论(0)
提交回复
热议问题