iterate through colors in javascript

前端 未结 3 846
终归单人心
终归单人心 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: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(',') + ')');
                }
            }
        }
    }
    

提交回复
热议问题