npm.nicfv.com
    Preparing search index...

    Custom Gradient

    This example takes you through creating your own custom color gradient and generate valid CSS code for it. It also shows how to generate intermediate color values in between color stops. By default, getColor() will assume a normalized input value from 0 to 1, but if minimum and maximum bounds are given, it will automatically interpolate between them.

    Follow these steps to create a new project workspace and install the viridis dependency to run this example.

    # Create and open project folder
    mkdir Custom_Gradient_demo
    cd Custom_Gradient_demo
    # Initialize project and install dependencies
    npm init -y
    npm i viridis@1.4.2
    # Create and open source file
    touch "Custom Gradient.mjs"
    open "Custom Gradient.mjs"

    Copy and paste this source code into Custom Gradient.mjs.

    import { Color, Gradient } from 'viridis';

    // Define a custom gradient using an array of colors
    const RGB_Gradient = new Gradient([
    new Color(255, 0, 0), // 0.0
    new Color(0, 255, 0), // 0.5
    new Color(0, 0, 255), // 1.0
    ]);

    // Generate valid CSS code for this color gradient
    console.log('CSS code : ' + RGB_Gradient);
    console.log('CSS code [45deg]: ' + RGB_Gradient.toString('linear', 1, ['45deg']));

    // Show the internal array of color stops
    console.log('Color Stops', RGB_Gradient.colors.join(','));

    // Generate a short list of intermediate color values
    // Gradient will automatically interpolate if given
    // a minimum and maximum bound. (1, N)
    const N = 5;
    for (let i = 1; i <= N; i++) {
    console.log(i + ' = ' + RGB_Gradient.getColor(i, 1, N));
    }

    In Custom_Gradient_demo/, execute Custom Gradient.mjs with NodeJS to generate an output.

    node "Custom Gradient.mjs"
    

    You should expect to see an output similar to the one below.

    CSS code        : linear-gradient(#FF0000,#00FF00,#0000FF)
    CSS code [45deg]: linear-gradient(45deg,#FF0000,#00FF00,#0000FF)
    Color Stops #FF0000,#00FF00,#0000FF
    1 = #FF0000
    2 = #7F7F00
    3 = #00FF00
    4 = #007F7F
    5 = #0000FF