commented color.ts file

This commit is contained in:
waltem01 2022-08-07 19:02:13 +02:00
parent d36f05a3d0
commit d3016684f3

View File

@ -1,26 +1,31 @@
// Interface to represent color objects
export interface Color {
r: number;
g: number;
b: number;
}
// Get black or white hex color depending on contrast (luminance)
export function getContrastColor(hexColor: string): string {
const rgb = hexToRgb(hexColor);
const luminance = getLuminance(rgb ?? ({ r: 0, g: 0, b: 0 } as Color));
return luminance > 0.5 ? '000000' : 'FFFFFF';
}
// Convert hex color to rgb color object
export function hexToRgb(hex: string): Color | null {
// Split string everz two characters, extract hex rgb values
const result = /^([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result
? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
}
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
}
: null;
}
// Get luminance value from rgb values of a color as defined by the Web Content Accessibility Guidelines (WCAG)
export function getLuminance(rgb: Color): number {
const a = [rgb.r, rgb.g, rgb.b].map((v) => {
v /= 255;
@ -29,8 +34,9 @@ export function getLuminance(rgb: Color): number {
return 0.2126 * a[0] + 0.7152 * a[1] + 0.0722 * a[2];
}
// Convert an rgb color object to a hex color string
export function rgbToHex(color: Color): string {
return (Object.entries(color) as [string, number][])
.map((e) => e[1].toString(16).padStart(2, '0'))
return [color.r, color.g, color.b]
.map((e) => e.toString(16).padStart(2, '0'))
.join('');
}