zahma
zahma

Reputation: 422

Interpolation of Colors

I want to interpolate between 2 colors and, given a specific number, generate an array with that number of interpolated colors.

I found that D3 has a method called d3.interpolate(), but I don't know how to use it.

How can I use D3 interpolator to generate an array of colours given the two colors to interpolate and the number of desired interpolated colors?

Upvotes: 5

Views: 6927

Answers (2)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

For using a D3 interpolator you just need to understand that the argument you'll pass to the interpolator varies from 0 to 1. The API is clear:

The returned function i is called an interpolator. Given a starting value a and an ending value b, it takes a parameter t in the domain [0, 1] and returns the corresponding interpolated value between a and b. An interpolator typically returns a value equivalent to a at t = 0 and a value equivalent to b at t = 1.

So, given this interpolator, going from red to green:

var colorInterpolator = d3.interpolateRgb("red", "green");

We just need to pass the values going from 0 to 1. For example, to create an array with 7 colors, we'll pass these values to the interpolator:

[0, 0.16, 0.33, 0.5, 0.66, 0.83, 1]

Check this demo:

var colorInterpolator = d3.interpolateRgb("red", "green");

var steps = 7;

var colorArray = d3.range(0, (1 + 1 / steps), 1 / (steps - 1)).map(function(d) {
  return colorInterpolator(d)
});

console.log(colorArray)
<script src="https://d3js.org/d3.v4.min.js"></script>

Now, let's see the colors in that array:

var colorInterpolator = d3.interpolateRgb("red", "green");

var steps = 7;

var colorArray = d3.range(0, (1 + 1 / steps), 1 / (steps - 1)).map(function(d) {
  return colorInterpolator(d)
});

d3.select("body").selectAll(null)
  .data(colorArray)
  .enter()
  .append("div")
  .attr("class", "myDivs")
  .style("background-color", String)
.myDivs {
  width: 40px;
  height: 40px;
  margin-right: 5px;
  display: inline-block;
}
<script src="https://d3js.org/d3.v4.min.js"></script>

Upvotes: 5

Hugues Stefanski
Hugues Stefanski

Reputation: 1182

You might want to check d3-color to see how colors are manipulated and interpolated within d3

Upvotes: 0

Related Questions