Generate color palette using JavaScript

18,408

Cycle through the fractions for each color like so:

function createColorPalette(value) {
    var v = 255/value;
    for( var rStep = 0, r = 0; rStep < v; rStep++) {    
        for( var gStep = 0, g = 0; gStep < v; gStep++ ) {       
            for( var bStep = 0, b = 0; bStep < v; bStep++ ) {                                                  
                createDiv(r,g,b);
                b += value;
            }
            g += value;
        }
        r += value;
    }
    createBr();
}
Share:
18,408
user1087110
Author by

user1087110

Updated on June 04, 2022

Comments

  • user1087110
    user1087110 almost 2 years

    I want to generate a color palette of every 5th, 15th,17th or 51th RGB-value.

    Something like this:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <title>Color Palette</title>
    <style type="text/css">
    div{margin:0;width:20px;height:20px;float:left}
    .clear{clear:both}
    </style>
    </head>
    <body>
    <script>
    var r = 0,
        g = 0,
        b = 0;
    
    function createBr() {
        var b = document.createElement('br');
        b.style.clear = 'both';
        document.body.appendChild(b);
    }
    
    function createDiv(r,g,b) {
    var a = document.createElement('div');
    a.style.background = 'rgb(' + r + ',' + g + ',' + b + ')';
    document.body.appendChild(a);
    }
    
    
    function createColorPalette(value) {
    var v = 255/value;
        for(i = 0; i < v; i++) {
            r = r + value;
            g = g + value;
            b = b + value;
            createDiv(r,g,b);
        }
    createBr();
    }
    
    // put in 5,15,17 or 51 as value below
    window.onload = createColorPalette(17);
    </script>
    </body>
    </html>
    

    I'm not smart enough to figure out how to generate all the 3375 colors with a small script. Any ideas how to do that?

  • user1087110
    user1087110 almost 12 years
    You forgot an end tag. But not working any way. It only generates lots of white div tags.
  • matt3141
    matt3141 almost 12 years
    sorry, I think I've fixed it all. Not sure if this is what you intended for it to look like but I think it hits all of the colors.
  • user1087110
    user1087110 almost 12 years
    It was the answer on my question any way... Thanks :)
  • Xeoncross
    Xeoncross over 5 years
    Here is a demo codepen. This simple solution fails to both prevent similar colors from showing as well as keep them in spectrum order.