Javascript Color Palette Generator - Formula for generating array of intermediate colors in Javascript given two hex (#abc123) values?
Given 2 or 3 ba开发者_StackOverflowse colors, I am trying to generate intermediate colors, so that 2-3 becomes anywhere from 5 to 50, like this chart below.
Any ideas? I'm using Highcharts making a pie chart.
first, thanks to @Juho Vepsäläinen
I applyed to my project like this
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 new Color().setRGB(ret[0], ret[1], ret[2]).toString();
}
function lerpColors(begin, end, n) {
var ret = [];
for(var i = 0; i < n; i++) {
var fac = i / (n - 1);
ret.push(lerp(begin.toRGBArray(), end.toRGBArray(), fac));
}
return ret;
}
var paletteSize = 300;
var palette = lerpColors(
new Color('#C6DBEF'),
new Color('#3182BD'),
paletteSize
);
console.log(palette) will show like below(example):
['002b36', '073642', '586e75', '657b83', '839496', '93a1a1', 'eee8d5', 'fdf6e3']
Core idea: use linear interpolation.
Example:
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);
You could do a linear interpolation between two colors, say (r1,g1,b1) to (r2,g2,b2). Use a parameter t that takes values 0-1. You get a smooth transition between the two colors by using (r,g,b)=(r1,g1,b1)+(r2-r1,g2-g1,b2-b1)*t
精彩评论