Last active
March 2, 2024 22:14
-
-
Save gskema/2f56dc2e087894ffc756c11e6de1b5ed to your computer and use it in GitHub Desktop.
Generate gradient color from 2 or 3 colors using JavaScript. Example: https://jsfiddle.net/e18g5f3L/
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
/** | |
* You may use this function with both 2 or 3 interval colors for your gradient. | |
* For example, you want to have a gradient between Bootstrap's danger-warning-success colors. | |
*/ | |
function colorGradient(fadeFraction, rgbColor1, rgbColor2, rgbColor3) { | |
var color1 = rgbColor1; | |
var color2 = rgbColor2; | |
var fade = fadeFraction; | |
// Do we have 3 colors for the gradient? Need to adjust the params. | |
if (rgbColor3) { | |
fade = fade * 2; | |
// Find which interval to use and adjust the fade percentage | |
if (fade >= 1) { | |
fade -= 1; | |
color1 = rgbColor2; | |
color2 = rgbColor3; | |
} | |
} | |
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 + ')'; | |
} |
Thanks for this. Quickly converted it to TypeScript if anyone is interested:
interface RGBColor {
red: number;
green: number;
blue: number;
}
export const colorGradient = (
fadeFraction: number,
rgbColor1: RGBColor,
rgbColor2: RGBColor,
rgbColor3?: RGBColor
) => {
let color1 = rgbColor1;
let color2 = rgbColor2;
let fade = fadeFraction;
// Do we have 3 colors for the gradient? Need to adjust the params.
if (rgbColor3) {
fade = fade * 2;
// Find which interval to use and adjust the fade percentage
if (fade >= 1) {
fade -= 1;
color1 = rgbColor2;
color2 = rgbColor3;
}
}
let diffRed = color2.red - color1.red;
let diffGreen = color2.green - color1.green;
let diffBlue = color2.blue - color1.blue;
let gradient = {
red: Math.floor(color1.red + diffRed * fade),
green: Math.floor(color1.green + diffGreen * fade),
blue: Math.floor(color1.blue + diffBlue * fade),
};
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
Thank you so much for this, it really help me !
I took the liberty of repeating your work in my own way on this pen : https://codepen.io/Zyr0/pen/dyZXepz