Create a hexadecimal colour based on a string with JavaScript

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

    Yet another solution for random colors:

    function colorize(str) {
        for (var i = 0, hash = 0; i < str.length; hash = str.charCodeAt(i++) + ((hash << 5) - hash));
        color = Math.floor(Math.abs((Math.sin(hash) * 10000) % 1 * 16777216)).toString(16);
        return '#' + Array(6 - color.length + 1).join('0') + color;
    }
    

    It's a mixed of things that does the job for me. I used JFreeman Hash function (also an answer in this thread) and Asykäri pseudo random function from here and some padding and math from myself.

    I doubt the function produces evenly distributed colors, though it looks nice and does that what it should do.

    0 讨论(0)
提交回复
热议问题