You have the right idea, you just need to process each R/G/B color channel. For example, in vanilla JavaScript you can do the following:
var a = [255, 0, 0], // First color
b = [0, 0, 255], // Other color
bands = 5, // Bands is the length of your domain
i,
delta = []; // Difference between color in each channel
// Compute difference between each color
for (i = 0; i < 4; i++){
delta[i] = (a[i] - b[i]) / (bands + 1);
}
// Use that difference to create your bands
for (i = 0; i <= bands + 1; i++){
var r = Math.round(a[0] - delta[0] * i);
var g = Math.round(a[1] - delta[1] * i);
var b = Math.round(a[2] - delta[2] * i);
console.log("<div style='background-color: #" + dec2hex(r) + dec2hex(g) + dec2hex(b) + "'>Band " + i + "</div>");
}
// A helper function for formatting
function dec2hex(i) {
return (i+0x100).toString(16).substr(-2).toUpperCase();
}
According to the d3 documentation, you can extract each color channel using the r
, g
and b
attributes of a color object:
# d3.rgb(color)
Constructs a new RGB color by parsing the specified color string. If color is not a string, it is coerced to a string; thus, this constructor can also be used to create a copy of an existing color, or force the conversion of a d3.hsl color to RGB.
...
The resulting color is stored as red, green and blue integer channel values in the range [0,255]. The channels are available as the r, g and b attributes of the returned object.
So at the top of the example above, you could say:
var myColor = d3.rgb("blue"),
a = [myColor.r, myColor.g, myColor.b],
...
Does that help?