npm.nicfv.com

    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 Gradient_demo
    cd Gradient_demo
    # Initialize project and install dependencies
    npm init -y
    npm i viridis@1.1.8
    # Create and open source file
    touch "Gradient.mjs"
    open "Gradient.mjs"

    Copy and paste this source code into 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(45));

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

    // 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 Gradient_demo/, execute Gradient.mjs with NodeJS to generate an output.

    node "Gradient.mjs"
    

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

    CSS code        : linear-gradient(90deg,rgba(255,0,0,100%),rgba(0,255,0,100%),rgba(0,0,255,100%))
    CSS code [45deg]: linear-gradient(45deg,rgba(255,0,0,100%),rgba(0,255,0,100%),rgba(0,0,255,100%))
    Color Stops [
      Color { red: 255, green: 0, blue: 0, alpha: 100 },
      Color { red: 0, green: 255, blue: 0, alpha: 100 },
      Color { red: 0, green: 0, blue: 255, alpha: 100 }
    ]
    1 = rgba(255,0,0,100%)
    2 = rgba(127,127,0,100%)
    3 = rgba(0,255,0,100%)
    4 = rgba(0,127,127,100%)
    5 = rgba(0,0,255,100%)
    
    MMNEPVFCICPMFPCPTTAAATR