使用 JavaScript 生成调色板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11162664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:14:18  来源:igfitidea点击:

Generate color palette using JavaScript

javascriptcolors

提问by user1087110

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

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

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?

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

采纳答案by matt3141

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