admin管理员组

文章数量:1328337

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?

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?

Share Improve this question edited Aug 24, 2017 at 13:24 Gerardo Furtado 102k9 gold badges128 silver badges177 bronze badges asked Aug 24, 2017 at 9:19 zahmazahma 4224 silver badges17 bronze badges 1
  • 2 You had no question in your post, just a statement, almost a moaning. I edited it to a meaningful question. – Gerardo Furtado Commented Aug 24, 2017 at 13:27
Add a ment  | 

2 Answers 2

Reset to default 5

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/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/d3.v4.min.js"></script>

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

本文标签: javascriptInterpolation of ColorsStack Overflow