Search code examples
javascriptrandomcolorsshadercode-snippets

javascript generate similar random color (shader || Tint || Monochromatic )


(HI) I am not a specialist in colorimetry, but I would like to know how to realize a script that generates random colors, but based on a master color.

maybe the random Shades or Tints

Ex:of #f25f9a. http://www.color-hex.com/color/f25f9a

#f25f9a
#f36fa4
#f47eae
#f58fb8
#f79fc2
#f8afcc
#f9bfd6
#fbcfe0
#fcdfea
#fdeff4
#ffffff

so i need to make a random color

function colors() { return ('0x' + Math.floor(Math.random() * 16777215).toString(16) || 0xffffff) };

and after that convert it to hex

function ColorToHex(hexb){return '#'+hexb.slice(2);}

then generate random tint or shader or Monochromatic Colors based on the ColorToHex it for a plugin developement with frames for debugging sprite.

thank for help , if you know any snippets?.


Solution

  • You could take the delta of a single color to 255 as variable part for random multiplication. Take the same random value for every color and build a string in the wanted format.

    function getRandomColor(color) {
        var p = 1,
            temp,
            random = Math.random(),
            result = '#';
    
        while (p < color.length) {
            temp = parseInt(color.slice(p, p += 2), 16)
            temp += Math.floor((255 - temp) * random);
            result += temp.toString(16).padStart(2, '0');
        }
        return result;
    }
    
    
    var color = '#f25f9a',
        i,
        rc;
    
    for (i = 0; i < 10; i++) {
        rc = getRandomColor(color);
        document.body.innerHTML += '<div style="background-color: ' + rc + ';">' + rc + '</div>';
    }