javascript 使用javascript创建独特的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6823286/
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-25 21:58:19  来源:igfitidea点击:

Create unique colors using javascript

javascripthistogram

提问by Kartik Dinesh

What is the best way to pick random colors for a bar chart / histogram such that each color is different from the other.. and possibly in contrast

为条形图/直方图选择随机颜色的最佳方法是什么,使每种颜色彼此不同......并且可能形成对比

The most talked about way is

谈论最多的方式是

'#'+(Math.random()*0xFFFFFF<<0).toString(16);

but this can generate similar colors.. and sometimes distinguishing them might be a problem.. Example enter image description here

但这会产生相似的颜色..有时区分它们可能是一个问题..示例 在此处输入图片说明

采纳答案by slaphappy

The best way is to convert from HSV values. You can divide the maximum value of "Hue" by the amount of colors you need and then increment by this result.

最好的方法是从HSV 值转换。您可以将“色调”的最大值除以您需要的颜色数量,然后以此结果递增。

For improved contrast, you can also alternate between high and low values of lightness.

为了提高对比度,您还可以在高亮度值和低亮度值之间交替。

回答by H?vard

I would generate colors using HSV(hue, saturation, value) instead of RGB. In HSV, the color is defined by the hue, ranging from 0-360. Thus, if you want e.g. 6different colors, you can simply divide 360by 5(because we want to include 0) and get 72, so each color should increment with 72. Use a function like this oneto convert the generated HSV color to RGB.

我会使用HSV(色调、饱和度、值)而不是 RGB来生成颜色。在 HSV 中,颜色由色调定义,范围为 0-360。因此,如果你想如6不同的颜色,你可以简单地划分3605(因为我们希望包括0)和获得72,所以每个颜色应与增加72。使用函数像这样一个所产生的HSV颜色转换为RGB。

The following function returns an array of totaldifferent colors in RGB format. Note that the colors won't be "random" in this example, as they will always range from red to pink.

以下函数total以 RGB 格式返回不同颜色的数组。请注意,在此示例中颜色不会是“随机的”,因为它们的范围始终从红色到粉红色。

function randomColors(total)
{
    var i = 360 / (total - 1); // distribute the colors evenly on the hue range
    var r = []; // hold the generated colors
    for (var x=0; x<total; x++)
    {
        r.push(hsvToRgb(i * x, 100, 100)); // you can also alternate the saturation and value for even more contrast between the colors
    }
    return r;
}

回答by Joe Nelson

The existing answers which mention the Hue, Saturation, Value representation of colors are very elegant, are closer to how humans perceive color, and it is probably best to follow their advice. Also creating a long precalculated list of colors and choosing subsets of them as needed is fast and reliable.

提到颜色的色相、饱和度、值表示的现有答案非常优雅,更接近人类对颜色的看法,最好听从他们的建议。此外,创建一个长长的预先计算的颜色列表并根据需要选择它们的子集是快速且可靠的。

However, here is some code that answers your question directly: it will generate random colors in RGB that are sufficiently different. There are two drawbacks to this technique that I can see. First, these colors are really random and could look kind of gross together, and second it might take a while for the code to stumble on colors that work, depending on how "far apart" you require the colors to be.

但是,这里有一些代码可以直接回答您的问题:它将在 RGB 中生成足够不同的随机颜色。我可以看到这种技术有两个缺点。首先,这些颜色确实是随机的,放在一起可能看起来有点粗糙,其次,代码可能需要一段时间才能偶然发现有效的颜色,这取决于您要求颜色“相距多远”。

function hex2rgb(h) {
    return [(h & (255 << 16)) >> 16, (h & (255 << 8)) >> 8, h & 255];
}
function distance(a, b) {
    var d = [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
    return Math.sqrt((d[0]*d[0]) + (d[1]*d[1]) + (d[2]*d[2]));
}
function freshColor(sofar, d) {
    var n, ok;
    while(true) {
        ok = true;
        n = Math.random()*0xFFFFFF<<0;
        for(var c in sofar) {
            if(distance(hex2rgb(sofar[c]), hex2rgb(n)) < d) {
                ok = false;
                break;
            }
        }
        if(ok) { return n; }
    }
}
function getColors(n, d) {
    var a = [];
    for(; n > 0; n--) {
        a.push(freshColor(a, d));
    }
    return a;
}

The distance between colors is the Euclidean distancemeasured by the R, G, and B components. Thus the furthest that two colors (black and white) can be is about 441.67.

颜色之间的距离是由 R、G 和 B 分量测量的欧几里得距离。因此,两种颜色(黑色和白色)的最远距离约为 441.67。

To use this code, call getColorswhere the first parameter is the number of colors, and the second is the minimum distance between any two of them. It will return an array of numerical RGB values.

要使用此代码,请调用getColorswhere 第一个参数是颜色的数量,第二个参数是其中任意两个之间的最小距离。它将返回一个数字 RGB 值数组。

回答by Paul

'#'+(Math.random()*0xFFFFFF<<0).toString(16);

Isn't the best method to use because it can generate values like #4567which is missing two digits instead of generating #004567

不是最好的方法,因为它可以生成#4567缺少两位数的值,而不是生成 #004567

It's better to pick each character individually like:

最好单独选择每个字符,例如:

'#'+Math.floor(Math.random()*16).toString(16)+
    Math.floor(Math.random()*16).toString(16)+
    Math.floor(Math.random()*16).toString(16)+
    Math.floor(Math.random()*16).toString(16)+
    Math.floor(Math.random()*16).toString(16)+
    Math.floor(Math.random()*16).toString(16);

But that can easily be reduced to picking three numbers since hex colours can be shortened. IE. #457== #445577

但这很容易简化为选择三个数字,因为可以缩短十六进制颜色。IE。#457==#445577

Then if you want to decrease the number of posibilities and widen the gap between them you can use:

然后,如果您想减少可能性的数量并扩大它们之间的差距,您可以使用:

'#'+(5*Math.floor(Math.random()*4)).toString(16)+
    (5*Math.floor(Math.random()*4)).toString(16)+
    (5*Math.floor(Math.random()*4)).toString(16);

Which divides the number of choices for each color by 5, and then evens out the distribution equally.

它将每种颜色的选择数除以 5,然后平均分配。

回答by Nicholas Evans

I like using hsl values for specifying colour this way.

我喜欢使用 hsl 值以这种方式指定颜色。

So

所以

"color: hsl(" + getRandomArbitary(0, 360) + ", 50%, 50%)";

would give you random results, but that won't give you your distinct separations. So I'd base it on the i value of a loop. Something like,

会给你随机结果,但这不会给你明显的分离。所以我将它基于循环的 i 值。就像是,

for (var i = 0; i < whateverYourValue; i += 1) {
    color = "color: hsl(" + i * 10 + ", 50%, 50%)";

    // set your colour on whatever
}

obviously the above is indicative, and not valid code on it's own.

显然以上是指示性的,它本身不是有效的代码。

Want to know more on hsl? Check http://mothereffinghsl.com/'cause, you know, it's fun.

想了解更多有关 hsl 的信息?检查http://mothereffinghsl.com/因为,你知道,这很有趣。

回答by fvu

I second what kbok and Harpyon say about working in HSV colorspace, and this little librarymakes it super easy to switch between RGB and HSV - and others.

我赞同 kbok 和 Harpyon 关于在 HSV 色彩空间中工作的看法,这个小库使得在 RGB 和 HSV 之间切换非常容易 - 以及其他。