-
-
Save joocer/bf1626d38dd74fef9d9e5fb18fef517c to your computer and use it in GitHub Desktop.
Generate gradient color from an arbitrary number of colors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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