Skip to content

Instantly share code, notes, and snippets.

@Landerson352
Created September 15, 2019 16:54
Show Gist options
  • Select an option

  • Save Landerson352/89f638203a7b60ff82a7b5113439e20d to your computer and use it in GitHub Desktop.

Select an option

Save Landerson352/89f638203a7b60ff82a7b5113439e20d to your computer and use it in GitHub Desktop.
A utility for mixing two hex colors.
const mixHexColors = (color1, color2, weight = 50) => {
function d2h(d) { return d.toString(16); } // convert a decimal value to hex
function h2d(h) { return parseInt(h, 16); } // convert a hex value to decimal
let color = '#';
for (let i = 0; i <= 5; i += 2) { // loop through each of the 3 hex pairs—red, green, and blue
const v1 = h2d(color1.replace('#', '').substr(i, 2)); // extract the current pairs
const v2 = h2d(color2.replace('#', '').substr(i, 2));
// combine the current pairs from each source color, according to the specified weight
let val = d2h(Math.floor(v2 + (v1 - v2) * (weight / 100.0)));
while (val.length < 2) { val = '0' + val; } // prepend a '0' if val results in a single digit
color += val; // concatenate val to our new color string
}
return color; // PROFIT!
};
const getColorRange = ({ from, to, segments }) => {
const colors = [];
for (let i = 0; i < segments; i += 1) {
colors.push(mixHexColors(from, to, (100 * i) / segments));
}
return colors;
};
export { getColorRange, mixHexColors };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment