To convert a hexadecimal color string like "#FF0000" to its complementary color in TypeScript, you can follow these steps:
- Convert the hexadecimal color to RGB.
- Calculate the complementary color by inverting the RGB values.
- Convert the inverted RGB values back to a hexadecimal string.
Here’s a TypeScript function that accomplishes this:
function toComplementaryColor(hexColor: string): string {
// Remove the '#' symbol if present
hexColor = hexColor.replace(/^#/, '');
// Convert hex to RGB
const r = parseInt(hexColor.substring(0, 2), 16);
const g = parseInt(hexColor.substring(2, 4), 16);
const b = parseInt(hexColor.substring(4, 6), 16);
// Calculate complementary color by inverting RGB values
const complementaryR = 255 - r;
const complementaryG = 255 - g;
const complementaryB = 255 - b;
// Convert RGB back to hex
const toHex = (value: number) => {
const hex = value.toString(16);
return hex.length === 1 ? `0${hex}` : hex;
};
const complementaryHex = `#${toHex(complementaryR)}${toHex(complementaryG)}${toHex(complementaryB)}`;
return complementaryHex;
}
// Example usage:
const originalColor = "#FF0000"; // Red
const complementaryColor = toComplementaryColor(originalColor);
console.log(complementaryColor); // Output: "#00FFFF" (Cyan)
Explanation:
- Hex to RGB Conversion: The hexadecimal string is split into its red, green, and blue components. Each component is converted from a hexadecimal string to a decimal number using
parseInt.
- Complementary Color Calculation: The complementary color is calculated by subtracting each RGB component from 255.
- RGB to Hex Conversion: The inverted RGB values are converted back to a hexadecimal string, ensuring each component is two characters long by padding with a leading zero if necessary.
This function will correctly convert any valid 6-digit hexadecimal color string to its complementary color.