选择两种颜色并在其间获得n种颜色

时间:2022-09-06 15:22:32

I want to pick a given number of colors within a boundary. For example I give #fff and #000 as boundaries and want 5 colors in between. How do I achieve to get #fff, color 2, ..., color5, #000, spread out evenly?

我想在边界内选择一定数量的颜色。例如,我将#fff和#000作为边界,并希望它们之间有5种颜色。我如何实现#fff,color 2,...,color5,#000,均匀展开?

I want to pick colors for a charting tool based on a dynamic number of items in the chart. Just wondering is this can be done easily with code, or maybe there's an online tool for this already? Otherwise I'll manually pick the colors ;)

我想根据图表中动态数量的项目为图表工具选择颜色。只是想知道这可以通过代码轻松完成,或者可能已经有了一个在线工具吗?否则我会手动挑选颜色;)

2 个解决方案

#1


1  

You could write a function which gets an interval and makes an array with the interval and their multiples.

您可以编写一个获取间隔的函数,并使用间隔及其倍数创建一个数组。

function getInbetweenColors(color1, color2, count) {
    var array = [color1],
        c1 = parseInt(color1.substring(1), 16),
        c2 = parseInt(color2.substring(1), 16),
        interval = (c2 - c1) / count,
        i;

    for (i = 1; i < count; i++) {         
        array[i] = Math.floor(c1 + i * interval).toString(16);
        while(array[i].length < color1.length-1) {
           array[i]= '0' + array[i];
        }
        array[i]= '#' + array[i];
    }
    array[count] = color2;
    return array;
}

document.write('<pre>' + JSON.stringify(getInbetweenColors('#fff', '#000', 5), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(getInbetweenColors('#0391f5', '#27333d', 5), 0, 4) + '</pre>');

#2


1  

chroma.js is an amazing library to do just that! - check out the .scale method here

chroma.js是一个令人惊叹的图书馆! - 在这里查看.scale方法

#1


1  

You could write a function which gets an interval and makes an array with the interval and their multiples.

您可以编写一个获取间隔的函数,并使用间隔及其倍数创建一个数组。

function getInbetweenColors(color1, color2, count) {
    var array = [color1],
        c1 = parseInt(color1.substring(1), 16),
        c2 = parseInt(color2.substring(1), 16),
        interval = (c2 - c1) / count,
        i;

    for (i = 1; i < count; i++) {         
        array[i] = Math.floor(c1 + i * interval).toString(16);
        while(array[i].length < color1.length-1) {
           array[i]= '0' + array[i];
        }
        array[i]= '#' + array[i];
    }
    array[count] = color2;
    return array;
}

document.write('<pre>' + JSON.stringify(getInbetweenColors('#fff', '#000', 5), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(getInbetweenColors('#0391f5', '#27333d', 5), 0, 4) + '</pre>');

#2


1  

chroma.js is an amazing library to do just that! - check out the .scale method here

chroma.js是一个令人惊叹的图书馆! - 在这里查看.scale方法