Aside: RGB is not a perceptually linear color space. I recommend converting from RGB to HSL, interpolating, and then converting back to RGB. I wrote the following PHP code to generate arbitrary perceptually valid gradients; I suggest turning it into a service, which can then be called from PHP or AJAX if necessary.
You can get your last hex output as
$hexcol = col2string( RGBinterpolate("#ececec", "#ffffff", 0.5) ); // "#f4f4f4"
Code:
// Input: // $start as RGB color string, // $end as RGB color string, // $dist as float in [0.0 .. 1.0] being % distance between start and end colors // Output: // array(int, int, int) being the resulting color in RGB) function RGBinterpolate( $start, $end, $dist ) { $hsl_start = rgb2hsl( getCol($start) ); $hsl_end = rgb2hsl( getCol($end) ); // choose the shorter arc of the hue wheel! if ($hsl_start[0] > $hsl_end[0]) { if ($hsl_start[0] > $hsl_end[0] + 0.5) $hsl_start[0] -= 1.0; } else { if ($hsl_end[0] > $hsl_start[0] + 0.5) $hsl_end[0] -= 1.0; } // do linear interpolation in hsl color space $hs = interp( $hsl_start[0], $hsl_end[0], $dist ); $ss = interp( $hsl_start[1], $hsl_end[1], $dist ); $ls = interp( $hsl_start[2], $hsl_end[2], $dist ); return hsl2rgb( array( $hs, $ss, $ls ) ); } // Input: start-value, end-value, % distance as float in [0.0 .. 1.0] // Output: result of interpolation as float function interp($start, $end, $dist) { return $start + ($end - $start)*$dist; } // Input: string in one of the following formats: //
source share