Last active
March 3, 2023 09:38
-
-
Save NachoToast/df41aec040d7c52ed8143d2ce656bdba to your computer and use it in GitHub Desktop.
Color gradient function for TypeScript.
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
/** Valid values are from 0 to 255 (inclusive) */ | |
export interface Colour { | |
red: number; | |
blue: number; | |
green: number; | |
} | |
/** Calculates an intermediary colour between 2 or 3 colours. | |
* @returns {Colour} Object with red, green, and blue number fields. | |
* @example -> {red: 123, blue: 255, green: 0} | |
*/ | |
export default function ColourGradient( | |
min: number, | |
max: number, | |
current: number, | |
colorA: Colour, | |
colorB: Colour, | |
colorC?: Colour, | |
): Colour { | |
let color_progression; | |
if (current >= max) color_progression = 1; | |
else color_progression = (current - min) / (max - min); // Standardize as decimal [0-1 (inc)]. | |
if (colorC) { | |
color_progression *= 2; | |
if (color_progression >= 1) { | |
color_progression -= 1; | |
colorA = colorB; | |
colorB = colorC; | |
} | |
} | |
const newRed = colorA.red + color_progression * (colorB.red - colorA.red); | |
const newGreen = colorA.green + color_progression * (colorB.green - colorA.green); | |
const newBlue = colorA.blue + color_progression * (colorB.blue - colorA.blue); | |
const red = Math.floor(newRed); | |
const green = Math.floor(newGreen); | |
const blue = Math.floor(newBlue); | |
return { red, green, blue }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment