getHighContrastComplementary

by John Wick

JavaScript

function getComplementaryColor(hex) {
  // Remove the hash (#) symbol if present
  hex = hex.replace('#', '');

  // Convert the hex color to RGB values
  const r = parseInt(hex.substring(0, 2), 16);
  const g = parseInt(hex.substring(2, 4), 16);
  const b = parseInt(hex.substring(4, 6), 16);

  // Calculate the complementary RGB values
  const compR = 255 - r;
  const compG = 255 - g;
  const compB = 255 - b;

  // Convert the complementary RGB values back to hex
  const compHex = `#${((1 << 24) | (compR << 16) | (compG << 8) | compB).toString(16).slice(1).toUpperCase()}`;

  return compHex;
}

function getHighContrastComplementary1(hex) {
  // Helper function: Converts hex color to RGB
  function hexToRgb(hex) {
    hex = hex.replace('#', '');
    return {
      r: parseInt(hex.substring(0, 2), 16),
      g: parseInt(hex.substring(2, 4), 16),
      b: parseInt(hex.substring(4, 6), 16)
    };
  }

  // Helper function: Converts RGB to hex
  function rgbToHex(r, g, b) {
    return `#${((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1).toUpperCase()}`;
  }

  // Helper function: Calculate the relative luminance of an RGB color
  function getLuminance({ r, g, b }) {
    const [R, G, B] = [r, g, b].map((v) => {
      v /= 255;
      return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
    });
    return 0.2126 * R + 0.7152 * G + 0.0722 * B;
  }

  // Helper function: Calculate contrast ratio between two luminances
  function getContrastRatio(lum1, lum2) {
    return lum1 > lum2 ? (lum1 + 0.05) / (lum2 + 0.05) : (lum2 + 0.05) / (lum1 + 0.05);
  }

  // Convert the original hex color to RGB
  const originalRgb = hexToRgb(hex);

  // Calculate the complementary RGB
  const complementaryRgb = {
    r: 255 - originalRgb.r,
    g: 255 - originalRgb.g,
    b: 255 - originalRgb.b
  };

  // Calculate luminance values for the original and complementary colors
  const originalLuminance = getLuminance(originalRgb);
  let complementaryLuminance =...