使用JavaScript生成调色板

时间:2012-06-22 19:11:58

标签: javascript colors

我想生成每第5,15,17或第51个RGB值的调色板。

这样的事情:

<!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>

我不够聪明,无法弄清楚如何使用小脚本生成所有3375种颜色。任何想法如何做到这一点?

1 个答案:

答案 0 :(得分:2)

循环显示每种颜色的分数,如下所示:

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();
}