Home  >  Article  >  Web Front-end  >  How to Lighten or Darken a Hex Color Code?

How to Lighten or Darken a Hex Color Code?

DDD
DDDOriginal
2024-11-08 05:06:01122browse

How to Lighten or Darken a Hex Color Code?

This code sample demonstrates a program that allows you to lighten or darken a hex color by a specific amount. You can provide a hex color as a string, such as "3F6D2A," and an integer representing the amount you want to adjust the color by, either lightening or darkening it.

Here's how the program works:

  1. It takes the hex color string and converts it into an integer.
  2. The integer is then adjusted by the specified amount, which can be positive to lighten the color or negative to darken it.
  3. The adjusted integer is converted back to a hex color string using a specific formula that ensures the color stays within the valid range.

Here's a simplified code snippet that explains how the color adjustment is done:

function LightenDarkenColor(col, amt) {
  col = parseInt(col, 16); // Convert hex color to integer
  col = col + amt; // Adjust the integer by the specified amount
  col = col.toString(16); // Convert the adjusted integer back to hex color
  return col;
}

In the provided function, there are multiple versions of the code, each with slight variations. The most notable difference is between the functions that use log blending and linear blending. Log blending typically produces more subtle and natural-looking color adjustments compared to linear blending.

To use the program, you can call the LightenDarkenColor function with the desired hex color and adjustment amount. For example, to lighten the color "3F6D2A" by 40, you would call:

LightenDarkenColor("3F6D2A", 40)

This would return a new hex color that is 40 units lighter than the original color.

The above is the detailed content of How to Lighten or Darken a Hex Color Code?. 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