delights / color
Convert and randomly generate good looking colors like a breeze
4.0.0
2024-03-16 17:25 UTC
Requires
- php: ^8.3
- savvot/random: ^v0.3.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3
- pestphp/pest: ^v2.34
- phpstan/phpstan: ^1
- spatie/pest-plugin-snapshots: ^2.1
- symfony/var-dumper: ^7
README
Installation
Requires PHP 8.3+
You can install the package via composer:
composer require delights/color
Usage
Generating nice looking colors
You can generate colors on the fly:
use Delight\Color\Generator; Generator::one(); Generator::many(n: 10) Generator::manyLazily(n: 10_000)
You may force the generator to use a certain seed:
use Delight\Color\Generator; $avatarColor = Generator::one(seed: $email); // will always return the same color for the given seed.
This also works for Generator::many
and Generator::manyLazily
.
You may change the defaults used by the Generator
.
use Delight\Color\Generator; Generator::withDefaults( hue: [100, 200], saturation: [1, 20], lightness: [40, 60] );
Or some of the defaults
Generator::withDefaults( hue: [120, 140] // just restrict the hue but keep the saturation and lightness settings );
Working with color
use Delight\Color\Hsl; $color = new Hsl(100, 20, 20); $color = new Hsl(100, .2, .2); // automatically normalized to 0-100 Hsl::boundedRandom([0, 360], [0,100], [0,100], $seed) Hsl::random($seed); // Alphas are silently ignored. // Works with rgb, rgba, hsla, hex... // This accepts _CSS-like_ string, emphasis on _like_. Hsl::fromString('hsl(100, 20%, 20%)');
Converting a color
Print a CSS string in the given format.
$color->toHex(); $color->toRgb(); $color->toHsl();
Hue, saturation, lightness
$color->hue; # between 0-360 $color->saturation; # between 0-100 $color->lightness; # between 0-100
Red, green, blue
$color->colorChannels(); // returns [r, g, b] $color->red(); $color->green(); $color->blue();
Brightness, darkness
$color->isDark(); $color->isBright(); // Returns a new instance of the color $color->darken($percentage = 15); $color->lighten($percentage = 15);
Luminance
As in https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
$color->luminance();
Contrast
As in https://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef. Very useful for accessibility testing.
$color->contrast($otherColor);
Testing
composer test
PHP Color was created by Félix Dorn under the MIT license.