Skip to content

Instantly share code, notes, and snippets.

@joocer
Forked from gskema/color-gradient.js
Last active January 26, 2022 17:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joocer/bf1626d38dd74fef9d9e5fb18fef517c to your computer and use it in GitHub Desktop.
Save joocer/bf1626d38dd74fef9d9e5fb18fef517c to your computer and use it in GitHub Desktop.
Generate gradient color from an arbitrary number of colors
function colorGradient(colors, fadeFraction) {
if (fadeFraction >= 1) {
return colors[colors.length - 1]
} else if (fadeFraction <= 0) {
return colors[0]
}
let fade = fadeFraction * (colors.length - 1);
let interval = Math.trunc(fade);
fade = fade - interval
color1 = colors[interval];
color2 = colors[interval + 1]
var diffRed = color2.red - color1.red;
var diffGreen = color2.green - color1.green;
var diffBlue = color2.blue - color1.blue;
var gradient = {
red: parseInt(Math.floor(color1.red + (diffRed * fade)), 10),
green: parseInt(Math.floor(color1.green + (diffGreen * fade)), 10),
blue: parseInt(Math.floor(color1.blue + (diffBlue * fade)), 10),
};
return 'rgb(' + gradient.red + ',' + gradient.green + ',' + gradient.blue + ')';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment