Create a hexadecimal colour based on a string with JavaScript

后端 未结 13 958
旧时难觅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 17:54

    Here's a solution I came up with to generate aesthetically pleasing pastel colours based on an input string. It uses the first two chars of the string as a random seed, then generates R/G/B based on that seed.

    It could be easily extended so that the seed is the XOR of all chars in the string, rather than just the first two.

    Inspired by David Crow's answer here: Algorithm to randomly generate an aesthetically-pleasing color palette

    //magic to convert strings to a nice pastel colour based on first two chars
    //
    // every string with the same first two chars will generate the same pastel colour
    function pastel_colour(input_str) {
    
        //TODO: adjust base colour values below based on theme
        var baseRed = 128;
        var baseGreen = 128;
        var baseBlue = 128;
    
        //lazy seeded random hack to get values from 0 - 256
        //for seed just take bitwise XOR of first two chars
        var seed = input_str.charCodeAt(0) ^ input_str.charCodeAt(1);
        var rand_1 = Math.abs((Math.sin(seed++) * 10000)) % 256;
        var rand_2 = Math.abs((Math.sin(seed++) * 10000)) % 256;
        var rand_3 = Math.abs((Math.sin(seed++) * 10000)) % 256;
    
        //build colour
        var red = Math.round((rand_1 + baseRed) / 2);
        var green = Math.round((rand_2 + baseGreen) / 2);
        var blue = Math.round((rand_3 + baseBlue) / 2);
    
        return { red: red, green: green, blue: blue };
    }
    

    GIST is here: https://gist.github.com/ro-sharp/49fd46a071a267d9e5dd

提交回复
热议问题