Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A way to smoothly step through set colour stops in javascript/typescript
type Color = {
r: number;
g: number;
b: number;
};
export const interpolate = (t, n1, n2) => {
return (n2 - n1) * t + n1;
};
export const colorInterpolate = (t: number, color1: Color, color2: Color) => {
return {
r: interpolate(t, color1.r, color2.r),
g: interpolate(t, color1.g, color2.g),
b: interpolate(t, color1.b, color2.b)
};
};
/**
* Finds what would be the most relevant color
* in a color array most likely created by
* getInterpolatedColors
*
* @param {number} t
* @param {Color[]} colorArr
*
* @returns Color
*/
export const getClosestColor = (t: number, colorArr: Color[]) => {
return colorArr[Math.round((colorArr.length - 1) * t)];
};
/**
* Creates an array of stepped colors through an array of colors
*
* @param {Color[]} colors
* @param {number} granularity
*
* @returns {Color[]}
*/
export const getInterpolatedColors = (
colors: Color[] = [],
granularity = 100
): Color[] => {
let colorStop = 1 / (colors.length - 1);
let granularityStop = 1 / granularity;
let colorArr = [];
for (let i = 0; i <= 1; i += granularityStop) {
let t = (i % colorStop) / colorStop;
let currColorIdx = Math.floor(i / colorStop);
colorArr.push(
colorInterpolate(t, colors[currColorIdx], colors[currColorIdx + 1])
);
}
return colorArr;
};
const colors = getInterpolatedColors(
[
new Color(233, 30, 99),
new Color(0, 188, 212),
new Color(255, 87, 34),
new Color(233, 30, 99), // add the same color last to smoothly restart, or dont
]
);
console.log(getClosestColor(0.5, colors))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment