iterate through colors in javascript

前端 未结 3 812
终归单人心
终归单人心 2021-01-06 09:02

I want to make a list of all colors used in css, however they seem to be stored in a base 16 format. I thought something like this might work, but it does not do what I wan

相关标签:
3条回答
  • 2021-01-06 09:36

    In JavaScript you can use "0x" before a number to make it hexadecimal and "0" to make it octal. Using this method, this should be the best code. This will probably crash your web browser, as there are 16,581,375 different possible hexadecimal colors in all of CSS. That's more than there are bytes in a megabyte (about 1 million), or how many years it would take to crack a 17-lowercase letter password.

    var colors = new Array();
    for(col=0x0;col<=0xFFFFFF;col++) {
      colors.push("#" + col);
    }
    
    0 讨论(0)
  • 2021-01-06 09:41

    Colors used in CSS 3 include 8 bits of each of red, green, blue, and an alpha channel that I believe is 8 bits (but is defined as a decimal number, so it's harder to tell). It's possible to represent these colors as rgba or hsla. With hexadecimal you can only represent 100% opaque colors. Iterating through eight bits of one color is easy enough:

    for (var i=0; i<256; i++) {
        var redChan = i;
    }
    

    To iterate through all the colors is possibly by nesting this loop four levels deep, but that makes some assumptions about exactly what direction you want to iterate in. It will also be quite a longwinded operation.

    // This is not intended to be the best solution, just to demonstrate the basic algorithm.
    for (var r=0; r<256; r++) {
        for (var g=0; g<256; g++) {
            for (var b=0; b<256; b++) {
                // Assume we have 8 bits of alpha to use.
                for (var a=0; a<256; a++) {
                    console.log('rgba(' + [r,g,b,a/255].join(',') + ')');
                }
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-06 09:45

    Colours in CSS are usually described by their red, green and blue values (as integers between 0-255), and sometimes an alpha value for transparency.

    If you're not interested in the alpha value, you write colours in CSS in the #RRGGBB hexadecimal format.

    If we forget that we're using groupings for red, green and blue, it can be seen that we're writing a number between 000000 (0) and FFFFFF (16777215). Therefore, you could describe every RGB colour as an integer in this range.

    var i = 0, colour;
    for (; i < 16777216; ++i) { // this is a BIG loop, will freeze/crash a browser!
        colour = '#' + ('00000' + i.toString(16)).slice(-6); // pad to 6 digits
        // #000000
        // #000001
        // ... #000100 ...
        // #FFFFFE
        // #FFFFFF
    }
    

    The above code loops over all 16777216 colours, so I'd advise against running such a loop, but you can see how it changes the integer in the range to a unique hex colour.

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