Skip to content

Instantly share code, notes, and snippets.

@sebdesign
Last active May 28, 2024 18:02
Show Gist options
  • Save sebdesign/a65cc39e3bcd81201609e6a8087a83b3 to your computer and use it in GitHub Desktop.
Save sebdesign/a65cc39e3bcd81201609e6a8087a83b3 to your computer and use it in GitHub Desktop.
<?php
class Color
{
/**
* Convert a hex color to RGB.
*
* @param string $hex #BADA55
* @return array{int,int,int} [186, 218, 85]
*/
public static function rgb(string $hex): array
{
return sscanf($hex, "#%02x%02x%02x");
}
/**
* Calculate the relative luminance of an RGB color.
*
* @param int $r
* @param int $g
* @param int $b
* @return float
*/
public static function luminance(int $r, int $g, int $b): float
{
return 0.2126 * pow($r/255, 2.2) +
0.7152 * pow($g/255, 2.2) +
0.0722 * pow($b/255, 2.2);
}
/**
* Calculate the relative luminance of two colors.
*
* @param string $C1 hex color
* @param string $C2 hex color
* @return float
*/
public static function relativeLuminance(string $C1, string $C2): float
{
$L1 = self::luminance(...self::rgb($C1));
$L2 = self::luminance(...self::rgb($C2));
if ($L1 > $L2) {
return ($L1 + 0.05) / ($L2 + 0.05);
} else {
return ($L2 + 0.05) / ($L1 + 0.05);
}
}
}
@sebdesign
Copy link
Author

// Check if white text against #bada55 background passes G18.
// https://www.w3.org/TR/2016/NOTE-WCAG20-TECHS-20160317/G18
return Color::relativeLuminance('#ffffff', '#bada55') >= 4.5;

@overclokk
Copy link

Hi, I think there is an issue, a contrast ratio between #ffffff and #bada55 is 1.58:1 https://webaim.org/resources/contrastchecker/?fcolor=ffffff&bcolor=BADA55

This is correct:

return Color::relativeLuminance('#000000', '#bada55') >= 4.5; // Return true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment