-
-
Save gskema/2f56dc2e087894ffc756c11e6de1b5ed to your computer and use it in GitHub Desktop.
/** | |
* 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 + ')'; | |
} |
This comment is useless. The function is fine ! Great work !
Thank you!! exactly what I needed
@gskema Cool function, thank you!
@elron yeah thanks bro
I'm not sure why you're thanking me, I did not create its. All thanks to @gskema
Exactly what I needed. Thanks
Is there any example on how this function works?
@Lathifahdhiya Made this just for you: https://jsfiddle.net/e18g5f3L/
@gskema Thank you!
Thanks for this, I used this to help build a gradient builder with an arbitrary number of colors by changing the start of the function: https://gist.github.com/joocer/bf1626d38dd74fef9d9e5fb18fef517c
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
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 + ")"
);
};
Useless