Lance Pollard Lance Pollard - 11 months ago 79
Javascript Question

Javascript Color Palette Generator - Formula for generating array of intermediate colors in Javascript given two hex (#abc123) values?

Given 2 or 3 base colors, I am trying to generate intermediate colors, so that 2-3 becomes anywhere from 5 to 50, like this chart below.

Trying to do this

Any ideas? I'm using Highcharts making a pie chart.


Core idea: use linear interpolation.


function lerp(a, b, fac) {
    var ret = [];

    for(var i = 0; i < Math.min(a.length, b.length); i++) {
        ret[i] = a[i] * (1 - fac) + b[i] * fac;

    return ret;

In addition you'll probably find it useful to have some form of abstraction for Color. You can get you color into a nicer form by instantiating it like "var col = new Color('#ff00ff');". After that you can access its rgb and hsv values easily.

Here's an example (untested) that shows how it should work in practice:

// this func returns n colors (begin, <interpolated colors>, end)
function lerpColors(begin, end, n) {
    var ret = [];

    for(var i = 0; i < n; i++) {
        var fac = i / (n - 1);

        ret.push(lerp(a.toRGBArray(), b.toRGBArray(), fac));

    return ret;

var col1 = new Color('#ff0011'); // some red
var col2 = new Color('#00ff11'); // some green

var colors = lerpColors(col1, col2, 7);