Given a start color and an end color, is it possible to algorithmically generate a range of colors between them? For example, given the light and dark shades of blue/gray at the start and end of the image below, how might I generate the intermediate shades?
One possible solution I am considering is to create a gradient from the two colors and then sample the color at equidistant points along that gradient. Is that likely to be the best approach?
Answer
This is called color interpolation. It is what gradients do under the hood. You can do so using a variety of means and methods, and exactly how the results are interpolated depends on the method.
I commonly do this for web projects using JavaScript so that I can change colors dynamically, such as in this music visualizer. A JavaScript implementation that has a very straightforward method of linear interpolation using RGB, pulled from the example above, is as follows:
// Returns a single rgb color interpolation between given rgb color
// based on the factor given; via https://codepen.io/njmcode/pen/axoyD?editors=0010
function interpolateColor(color1, color2, factor) {
if (arguments.length < 3) {
factor = 0.5;
}
var result = color1.slice();
for (var i = 0; i < 3; i++) {
result[i] = Math.round(result[i] + factor * (color2[i] - color1[i]));
}
return result;
};
// My function to interpolate between two colors completely, returning an array
function interpolateColors(color1, color2, steps) {
var stepFactor = 1 / (steps - 1),
interpolatedColorArray = [];
color1 = color1.match(/\d+/g).map(Number);
color2 = color2.match(/\d+/g).map(Number);
for(var i = 0; i < steps; i++) {
interpolatedColorArray.push(interpolateColor(color1, color2, stepFactor * i));
}
return interpolatedColorArray;
}
Which is used like so and returns an array of the interpolated colors:
var colorArray = interpolateColors("rgb(94, 79, 162)", "rgb(247, 148, 89)", 5);
You can also find PhotoShop (and likely other program) extensions for doing color interpolation. However, you might want to check to make sure the method of interpolation is the same one that you desire, as you can use any function to interpolate based on.
No comments:
Post a Comment