tinygradient-es
Easily generate color gradients with an unlimited number of color stops and steps.
This package is exported as es module
Thanks to Damien Mystic Sorel
Live demo
Installation
$ npm install tinygradient
Dependencies
Usage
The gradient can be generated using RGB or HSV interpolation. HSV usually produces brighter colors.
Initialize gradient
The tinygradient
constructor takes a list or an array of colors stops.
var gradient = tinygradient("red", "green", "blue");
var gradient = tinygradient(["#ff0000", "#00ff00", "#0000ff"]);
The colors are parsed with TinyColor, multiple formats are accepted.
var gradient = tinygradient([
tinycolor("#ff0000"),
{ r: 0, g: 255, b: 0 },
{ h: 240, s: 1, v: 1, a: 1 },
"rgb(120, 120, 0)",
"gold",
]);
You can also specify the position of each color stop (between 0
and 1
). If no position is specified, stops are distributed equidistantly.
var gradient = tinygradient([
{ color: "#d8e0de", pos: 0 },
{ color: "#255B53", pos: 0.8 },
{ color: "#000000", pos: 1 },
]);
Generate gradient
Each method takes at least the number of desired steps.
The generated gradients might have one more step in certain conditions.
var colorsRgb = gradient.rgb(9);

var colorsHsv = gradient.hsv(9);

var colorsHsv = gradient.hsv(9, true);

There are also two methods which will automatically choose between clockwise and counter-clockwise.
var colorsHsv = gradient.hsv(9, "short");
var colorsHsv = gradient.hsv(9, "long");
Each method returns an array of TinyColor objects, see available methods.
Get CSS gradient string
The css
method will output a valid W3C string (without vendors prefix) to use with background-image
CSS property.
var gradientStr = gradient.css();
var gradientStr = gradient.css("radial", "farthest-corner ellipse at top left");
Get color at a specific position
Returns a single TinyColor object from a defined position in the gradient (from 0 to 1).
colorAt55Percent = gradient.rgbAt(0.55);
colorAt55Percent = gradient.hsvAt(0.55);
Reversing gradient
Returns a new instance of TinyGradient with reversed colors.
var reversedGradient = gradient.reverse();
Loop the gradient
Returns a new instance of TinyGradient with looped colors.
var loopedGradient = gradient.loop();
Position-only stops
I is possible to define stops with the pos
property only and no color
. This allows to define the position of the mid-point between the previous and the next stop.
var gradient = tinygradient([
{ color: "black", pos: 0 },
{ pos: 0.8 },
{ color: "white", pos: 1 },
]);
License
This library is available under the MIT license.