Create a hexadecimal colour based on a string with JavaScript

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

    If your inputs are not different enough for a simple hash to use the entire color spectrum, you can use a seeded random number generator instead of a hash function.

    I'm using the color coder from Joe Freeman's answer, and David Bau's seeded random number generator.

    function stringToColour(str) {
        Math.seedrandom(str);
        var rand = Math.random() * Math.pow(255,3);
        Math.seedrandom(); // don't leave a non-random seed in the generator
        for (var i = 0, colour = "#"; i < 3; colour += ("00" + ((rand >> i++ * 8) & 0xFF).toString(16)).slice(-2));
        return colour;
    }
    

提交回复
热议问题