color_difference¶
The color_difference filter calculates a numerical representation of the perceived difference between two colors. This filter is useful when you need to determine how visually distinct two colors are, especially in scenarios where you want to ensure sufficient contrast or create harmonious color schemes.
Functionality
- Color Values: Takes two string arguments representing colors in Hex, RGB, or HSL format.
- Difference Calculation:
- Converts both colors to the RGB color space if necessary.
- Calculates the absolute differences between the corresponding red, green, and blue components of the two colors.
- Sums these differences to obtain a total color difference value.
- Output: Returns an integer value representing the total color difference. Higher values indicate greater differences between the colors.
Syntax
Arguments
- color2: A string representing the second color for comparison.
Code Samples
Example 1: Comparing Similar Colors
Output Example 2: Comparing Different Colors Output Example 3: Comparing Colors in Different FormatsOutput
Outliers and Special Cases¶
- Invalid Input: If either color input is invalid or in an unsupported format, the filter might return
nilor an error. - Zero Difference: A color difference of 0 indicates that the two colors are identical.
- Maximum Difference: The maximum possible color difference is 765, which occurs between black and white.
Key Points¶
- The
color_differencefilter provides a simple way to quantify the perceived difference between colors. - While not a perfect measure of visual distinction, it can be helpful for making design decisions and ensuring accessibility.
- Consider using this filter in conjunction with other color filters (e.g.,
color_brightness) to create more sophisticated color logic in your templates. - Remember that the calculated color difference is a relative value and may not perfectly align with human perception in all cases.