add color util

This commit is contained in:
Halit Aksoy 2022-06-04 17:15:28 +03:00
parent 3d50ee8697
commit b125632da0

51
src/util/ColorUtil.ts Normal file
View File

@ -0,0 +1,51 @@
//from this gist https://gist.github.com/jfsiii/5641126
// from http://www.w3.org/TR/WCAG20/#relativeluminancedef
export function relativeLuminanceW3C(
R8bit: number,
G8bit: number,
B8bit: number
) {
const RsRGB = R8bit / 255;
const GsRGB = G8bit / 255;
const BsRGB = B8bit / 255;
const R =
RsRGB <= 0.03928 ? RsRGB / 12.92 : Math.pow((RsRGB + 0.055) / 1.055, 2.4);
const G =
GsRGB <= 0.03928 ? GsRGB / 12.92 : Math.pow((GsRGB + 0.055) / 1.055, 2.4);
const B =
BsRGB <= 0.03928 ? BsRGB / 12.92 : Math.pow((BsRGB + 0.055) / 1.055, 2.4);
// For the sRGB colorspace, the relative luminance of a color is defined as:
const L = 0.2126 * R + 0.7152 * G + 0.0722 * B;
return L;
}
export function relativeLuminanceW3CHexColor(hexColor: string): number {
const [r, g, b] = hexToRgb(hexColor);
return relativeLuminanceW3C(r, g, b);
}
// from https://www.codegrepper.com/code-examples/javascript/javascript+convert+color+string+to+rgb
export function rgbToHex(r: number, g: number, b: number): string {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
// from https://www.codegrepper.com/code-examples/javascript/javascript+convert+color+string+to+rgb
export function hexToRgb(
hex: string,
result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
): number[] {
return result ? result.map((i) => parseInt(i, 16)).slice(1) : null;
//returns [23, 14, 45] -> reformat if needed
}
export function getColorByLuminance(
color: string,
lightColor: string,
darkColor: string
): string {
return relativeLuminanceW3CHexColor(color) < 0.5 ? darkColor : lightColor;
}