javascript 循环浏览所有 rgb 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23954335/
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
Cycle through all rgb values
提问by user3387566
rgb range of 0-255 for each (red, green and blue) means that there should be 256x256x256 possible rgb colour values.
每个(红色、绿色和蓝色)的 rgb 范围为 0-255 意味着应该有 256x256x256 种可能的 rgb 颜色值。
How can I loop through and print every single value?
如何遍历并打印每个值?
I don't need a specific order yet I just want to know how to go through and get all values without skipping any.
我不需要特定的顺序,但我只想知道如何在不跳过任何值的情况下完成并获取所有值。
回答by h2ooooooo
You can simply use 3 nested loops:
您可以简单地使用 3 个嵌套循环:
var red, green, blue;
for (red = 0; red <= 255; red++) {
for (green = 0; green <= 255; green++) {
for (blue = 0; blue <= 255; blue++) {
// rgb(red, green, blue)
}
}
}
Order:
命令:
R | G | B
---------------
0 | 0 | 0
0 | 0 | 1
0 | 0 | 2
...............
255 | 255 | 253
255 | 255 | 254
255 | 255 | 255
An alternative is a loop that loops to 256 * 256 * 256 (16777216):
另一种方法是循环到 256 * 256 * 256 (16777216) 的循环:
var red, green, blue;
for (var rgb = 0; rgb <= 16777216; rgb++) {
red = (rgb >> 16) & 0xFF;
green = (rgb >> 8) & 0xFF;
blue = (rgb) & 0xFF;
// rgb(red, green, blue)
}
Here the order would be:
这里的顺序是:
R | G | B
---------------
0 | 0 | 0
1 | 0 | 0
2 | 0 | 0
...............
253 | 255 | 255
254 | 255 | 255
255 | 255 | 255
The performance won't be as good though, as you'd use a lot of logic.
但是,性能不会那么好,因为您会使用很多逻辑。
回答by Codor
It could be done with the follwing nested loops.
它可以通过以下嵌套循环来完成。
var r;
var g;
var b;
for ( r = 0; r <= 255; r++ )
{
for ( g = 0; g <= 255; g++ )
{
for ( b = 0; b <= 255; b++)
{
// output values of r, g and b
}
}
}