iterate through colors in javascript

前端 未结 3 842
终归单人心
终归单人心 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条回答
  •  Happy的楠姐
    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.

提交回复
热议问题