Create a hexadecimal colour based on a string with JavaScript

后端 未结 13 939
旧时难觅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))
    

提交回复
热议问题