Home >Web Front-end >CSS Tutorial >How do you generate the opposite color of a given color in terms of light or dark?

How do you generate the opposite color of a given color in terms of light or dark?

Susan Sarandon
Susan SarandonOriginal
2024-11-13 14:04:02950browse

How do you generate the opposite color of a given color in terms of light or dark?

Generating the Opposite Color from a Given Color

Problem:

How can I create a color that is opposite to the current color in terms of lightness or darkness? If the current color is black, I need to generate white, and vice versa.

Solution:

To achieve this functionality, we can utilize an algorithm that involves the following steps:

  1. Initially, we convert the current color from hexadecimal (HEX) format to its equivalent Red-Green-Blue (RGB) components.
  2. We then invert each of the R, G, and B components by subtracting their values from 255.
  3. The inverted RGB components are then converted back to HEX format.
  4. Finally, we pad each HEX component with leading zeros as necessary to ensure a valid output.

By following these steps, we can create a function named invertColor that takes a current HEX color as input and returns its opposite color:

function invertColor(hex) {
  // Convert HEX to RGB
  var r = parseInt(hex.slice(1, 3), 16);
  var g = parseInt(hex.slice(3, 5), 16);
  var b = parseInt(hex.slice(5, 7), 16);

  // Invert color components
  r = (255 - r).toString(16);
  g = (255 - g).toString(16);
  b = (255 - b).toString(16);

  // Pad each with zeros and return
  return "#" + padZero(r) + padZero(g) + padZero(b);
}

function padZero(str, len) {
  len = len || 2;
  var zeros = new Array(len).join("0");
  return (zeros + str).slice(-len);
}

This function takes into account the need to invert colors to create opposite shades of lightness or darkness.

Example:

If we pass the color "#F0F0F0" (a bright color) as an input to the invertColor function, it would return "#202020" (a dark color).

The above is the detailed content of How do you generate the opposite color of a given color in terms of light or dark?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn