CSS gradients are lacklusture.
Notice how transitioning from red to green leaves a dull greyish-brown color in the middle.
That's because these gradients are calculated using linear interpolation in the RGB space, leading to unnatural blending that doesn't model how colors blur in the real world.
This Gamma Gradients library provides two methods to produce vivid gradients in CSS.
Gamma-Correction: This method involves linear interpolation subsequent to gamma correction. The result is a gradient that aligns more closely with human visual perception in the real world.
HSL-Correction: By interpolating across the HSL color space, this method maintains richer hues than RGB interpolation.
npm install gamma-gradients
or
yarn add gamma-gradients
To start using the library, import the functions you need:
import {
getGammaGradientString,
calculateGammaCorrectedGradientSteps,
getHSLGradientString,
calculateHSLGradientSteps,
} from "gamma-gradients";
Generate a gradient that transitions linearly in perceived brightness. This is achieved by gamma correcting the gradient stops, then linearly interpolating between them, and finally undoing the gamma correction.
calculateGammaCorrectedGradientSteps(color1, color2, steps?, gamma?)
: Calculates the steps for a gamma-corrected gradient.getGammaGradientString(color1, color2, direction?, steps?, gamma?)
: Generates a CSS gradient string for a gamma-corrected gradient.
Example:
const gradient = getGammaGradientString("#FF0000", "#0000FF");
console.log(gradient);
Generate a gradient that transitions linearly in the HSL color space.
calculateHSLGradientSteps(color1, color2, steps?, reverse?)
: Calculates the steps for an HSL gradient. Thereverse
parameter helps determine the shortest path of transition.getHSLGradientString(color1, color2, direction?, steps?, reverse?)
: Generates a CSS gradient string for an HSL gradient.
Example:
const hslGradient = getHSLGradientString("#FF0000", "#00FF00");
console.log(hslGradient);
This library was inspried by a video from Henry Reich at MinutePhysics, which provides an explanation of gamma-corrected color blending.
Visit https://gradients.fnt.hm for a playground to explore the different parameters offered by these functions.
- Gradient corrections with more than 2 starting colors
- SASS plugin
If you're interested in contributing, feel free to open a pull request or raise issues on the GitHub repository.
This project is licensed under the MIT License.