Easy gradients for Chart.js

Overview

chartjs-plugin-gradient

Easy gradients for Chart.js

This plugin requires Chart.js 3.0.0 or later. Could work with v2, but it is not supported.

NOTE the plugin does not automatically register.

Example

Example chart

Installation

NPM:

npm i --save-dev chartjs-plugin-gradient

CDN:

<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-gradient"></script>

Usage

loading

ESM

import gradient from 'chartjs-plugin-gradient';

CDN

const gradient = window['chartjs-plugin-gradient'];

Registering

All charts

Chart.register(gradient);

Signle chart

const chart = new Chart(ctx, {
  // ...
  plugins: {
    gradient
  }
});

Configuration

The gradient colors are configured in the gradient key of dataset

const chart = new Chart(ctx, {
  data: {
    datasets: [{
      // data
      gradient: {
        backgroundColor: {
          axis: 'y',
          colors: {
            0: 'red',
            50: 'yellow',
            100: 'green'
          }
        },
        borderColor: {
          axis: 'x',
          colors: {
            0: 'black',
            1: 'white',
            2: 'black',
            3: 'white'
          }
        }
      }
    }]
  }
});

License

chartjs-plugin-gradient.js is available under the MIT license.

Comments
  • Add test cases for all axes types

    Add test cases for all axes types

    This PR is:

    1. adding test cases for all axes types
    2. adding chartjs-adapter-luxon and luxon dependencies (enabling tests on time axes)
    3. adding test-lint mpn command in order to add the lint test invoking npm test
    infrastructure 
    opened by stockiNail 22
  • Remove imported CHART.JS parts from distribution file

    Remove imported CHART.JS parts from distribution file

    Fix #17

    This PR excludes the CHART.JS parts from distribution file of the plugin. It removes also the direct dependency from @kurkle/color, leveraging on what it's included in CHART.JS.

    bug 
    opened by stockiNail 14
  • Add KARMA test suite to enable testing

    Add KARMA test suite to enable testing

    This PR is adding test suite in order to enable the tests.

    The source was chartjs-plugin-annotation and maybe something is not "perfect".

    What cannot do is to register the plugin globally (try in several ways without any success) therefore in this PR the plugin has been adding in the first test case.

    EDIT: the global registration was fixed putting it in beforeAll hook. Thanks @kurkle

    infrastructure 
    opened by stockiNail 10
  • Background Fill Wont Work In Vue.js 3

    Background Fill Wont Work In Vue.js 3

    Hey there I was looking around and founded your great plugin! but it only work on border and it wont fill under the line chart as expected! Here is my sample and these are my dependencies I use:

    PS: I'd be happy to help you fix the bug!

      "dependencies": {
        "vue": "^3.2.37",
        "vue-chartjs": "^4.1.1",
        "chartjs-plugin-gradient": "^0.5.1"
      },
      "devDependencies": {
        "@vitejs/plugin-vue": "^3.1.0",
        "typescript": "^4.6.4",
        "vite": "^3.1.0",
        "vue-tsc": "^0.40.4"
      }
    
    import { defineComponent, h, PropType } from 'vue'
    import gradient from 'chartjs-plugin-gradient';
    import { Line } from 'vue-chartjs'
    import {
      Chart as ChartJS,
      Title,
      Tooltip,
      Legend,
      LineElement,
      LinearScale,
      PointElement,
      CategoryScale,
      Plugin
    } from 'chart.js'
    
    ChartJS.register(
      gradient,
      Title,
      Tooltip,
      Legend,
      LineElement,
      LinearScale,
      PointElement,
      CategoryScale,
    )
    
    export default defineComponent({
      name: 'LineChart',
      components: {
        Line
      },
      props: {
        chartId: {
          type: String,
          default: 'line-chart'
        },
        width: {
          type: Number,
          default: 500
        },
        height: {
          type: Number,
          default: 400
        },
        cssClasses: {
          default: '',
          type: String
        },
        styles: {
          type: Object as PropType<Partial<CSSStyleDeclaration>>,
          default: () => {
            accentColor: 'yellow'
            backgroundColor: 'yellow'
          }
        },
        plugins: {
          type: Array as PropType<Plugin<'line'>[]>,
          default: () => []
        }
      },
      setup(props) {
        const chartData = {
          labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
          datasets: [
            {
              gradient: {
                backgroundColor: {
                  axis: 'y',
                  colors: {
                    0: 'red',
                    50: 'yellow',
                    100: 'green'
                  }
                },
                borderColor: {
                  axis: 'x',
                  colors: {
                    0: '#ffcb00',
                    1: 'black',
                    2: '#ffcb00',
                    3: 'black'
                  }
                }
              },
              tension: .4,
              data: [40, 39, 30, 40, 39, 50, 40]
            }
          ]
        }
    
        const chartOptions = {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              display: false
            },
            interaction: {
              mode: 'index',
            },
            layout: {
              padding: {
                left: 0,
                right: 0,
                top: 0,
                bottom: 0,
              },
            }
          },
          elements: {
            point: {
              radius: 0
            }
          },
        }
    
        return () =>
          h(Line, {
            chartData,
            chartOptions,
            chartId: props.chartId,
            width: props.width,
            height: props.height,
            cssClasses: props.cssClasses,
            styles: props.styles,
            plugins: props.plugins
          })
      }
    })
    
    opened by mhnayeb 7
  • Legend boxes don't reflect the gradient

    Legend boxes don't reflect the gradient

    Feature Proposal

    As I have seen in my lib, when you use gradients, the gradients are not reflected in the legend.

    To be precise, the gradient is applied to the legend but due to the gradient size is limited to the scales, the legend are out side of the gradient and then the canvas use the color related to the position.

    See example in codepen: https://codepen.io/stockinail/pen/xxpENVM

    As you can see the legend is using the red color because is the color from the gradient for legend position.

    The same is for polarArea (using the radial gradient) where all legend items are colored with the color of the gradient.

    polarGradient

    The proposal is to reflect on the legend the gradient.

    Possible Implementation

    I see only 1 option, creating a generateLabels callback in the plugin to set to the chart in order to create a specific gradient (with dimension of the legend box).

    For polarArea, the generateLabels callback could return the color at the data index, calculating the last color for the data index. For this, I have got already a code (even if is written in Java) that it can be translated and used.

    opened by stockiNail 6
  • Add support to time scale with colorStop option configured with formatted dates

    Add support to time scale with colorStop option configured with formatted dates

    Fix #15.

    This PR is enable the feature to use in color node color stop as formatted date, leveraging on scale parsing.

    Example:

    gradient: {
      backgroundColor: {
        axis: 'x',
          colors: {
            "05/30/2021": 'green',
            "06/02/2021": 'blue',
            "06/04/2021": 'red'
          }
        }
      }
    }
    

    Time scale options:

    scales: {
      x: {
        type: 'time', 
        time: {
          unit: 'day',
          parser: 'MM/dd/yyyy',
        }
      }
    }
    

    timeGradient

    enhancement 
    opened by stockiNail 6
  • gradient not working

    gradient not working

    Hello, I'm trying to use this plugin in my project and nothing is painted except for the legend

    component code:

    <template>
      <div class="index__dynamics">
        <div class="index__dynamics__wrapper">
    
    
          <div class="index__dynamics__title">
            <div class="index__dynamics__title__name">
              <img src="~assets/icon_dynamic.svg" alt="">
              Динамика общей оценки
            </div>
          </div>
    
          <div id="canvas-holder">
            <canvas id="chart-area" width="632" height="400"></canvas>
          </div>
    
    
          <div @click="qwe">click</div>
    
        </div>
      </div>
    </template>
    
    <script>
    import gradient from 'chartjs-plugin-gradient';
    import {
      Chart,
      ArcElement,
      LineElement,
      BarElement,
      PointElement,
      BarController,
      BubbleController,
      DoughnutController,
      LineController,
      PieController,
      PolarAreaController,
      RadarController,
      ScatterController,
      CategoryScale,
      LinearScale,
      LogarithmicScale,
      RadialLinearScale,
      TimeScale,
      TimeSeriesScale,
      Decimation,
      Filler,
      Legend,
      Title,
      Tooltip
    } from 'chart.js';
    
    Chart.register(
        ArcElement,
        LineElement,
        BarElement,
        PointElement,
        BarController,
        BubbleController,
        DoughnutController,
        LineController,
        PieController,
        PolarAreaController,
        RadarController,
        ScatterController,
        CategoryScale,
        LinearScale,
        LogarithmicScale,
        RadialLinearScale,
        TimeScale,
        TimeSeriesScale,
        Decimation,
        Filler,
        Legend,
        Title,
        Tooltip,
        gradient
    );
    
    export default {
      data() {
        return {
    
        }
      },
      mounted() {
    
      },
      methods: {
        qwe() {
          const ctx = document.getElementById('chart-area').getContext('2d');
          const gen = () => [...Array(10)].map((v, i) => ({x: i, y: rand()}));
          const rand = () => Math.random() * 100;
    
          window.chart = new Chart(ctx, {
            type: 'line',
            data: {
              datasets: [{
                label: 'gradient fill',
                data: gen(),
                gradient: {
                  backgroundColor: {
                    axis: 'y',
                    colors: {
                      0: 'red',
                      50: 'yellow',
                      100: 'green'
                    }
                  }
                }
              }]
            },
            options: {
              scales: {
                x: {
                  type: 'linear'
                }
              }
            },
            plugins: [
              gradient
            ]
          });
    
        }
      },
      components: {
      },
      props: {}
    }
    </script>
    
    `
    nuxt.config
    
    `
    import path from 'path'
    import fs from 'fs'
    
    export default {
        target: 'static',
        // Global page headers: https://go.nuxtjs.dev/config-head
        head: {
            title: 'coj',
            htmlAttrs: {
                lang: 'ru'
            },
            meta: [
                {charset: 'utf-8'},
                {name: 'viewport', content: 'width=device-width, initial-scale=1'},
                {hid: 'description', name: 'description', content: ''},
                {name: 'format-detection', content: 'telephone=no'}
            ],
            link: [
                {rel: 'icon', type: 'image/x-icon', href: '/favicon.ico'},
                {
                    rel: "stylesheet",
                    href: "https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800;900&family=Montserrat:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap",
                },
                {
                    rel: "preconnect",
                    href: "https://fonts.googleapis.com"
                },
                {
                    rel: "preconnect",
                    href: "https://fonts.gstatic.com",
                    crossorigin: ''
                }
            ]
        },
    
        vue: {
            config: {
                productionTip: false,
                devtools: true
            }
        },
    
        env: {
            stripeEnv: process.env.stripeEnv,
            stripePublicKey: process.env.stripePublicKey,
        },
    
        loading: { color: '#fff' },
    
        // Global CSS: https://go.nuxtjs.dev/config-css
        css: [
            "~layouts/global.css",
        ],
    
        // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
        plugins: [],
    
        // Auto import components: https://go.nuxtjs.dev/config-components
        components: true,
    
        // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
        buildModules: [
            '@nuxtjs/vuetify'
        ],
    
        // Modules: https://go.nuxtjs.dev/config-modules
        modules: [
            // https://go.nuxtjs.dev/bootstrap
            'bootstrap-vue/nuxt',
            '@nuxtjs/auth-next',
            '@nuxtjs/axios'
        ],
        axios: {
          debug: true
        },
        auth: {
            cookie: {
                prefix: 'auth.',
                options: {
                    secure: 'production'
                }
            },
            strategies: {
    
            },
            redirect: {
                home: false,
                callback: false,
                logout: false
            }
        },
        // Build Configuration: https://go.nuxtjs.dev/config-build
        build: {},
        server: {
            port: 35635, // default: 3000
            host: '0.0.0.0', // default: localhost,
            timing: false,
            https: {
                key: fs.readFileSync(path.resolve(__dirname, 'server.key')),
                cert: fs.readFileSync(path.resolve(__dirname, 'server.crt'))
            }
        }
    }
    
    `
    
    opened by lerinoi 4
  • Got some problems in console

    Got some problems in console

    react-dom.development.js?ac89:22839 Uncaught TypeError: Cannot read properties of undefined (reading 'datasetIndex') at updateLegendItems (chartjs-plugin-gradient.esm.js?52eb:223:1) at Object.afterUpdate (chartjs-plugin-gradient.esm.js?52eb:339:1)

    opened by beastovsk 4
  • Enable gradient styles on the legend items

    Enable gradient styles on the legend items

    Fix #28

    This PR is enabling to set fillStyle and strokeStyle on the legend items related to datasets where the gradient has been set.

    It is applying only backgroundColor and borderColor, if set.

    It doesn't go in exception on CHART.JS version 2.x but it can not enable the styles on legend items because the legend size calculation is done in a different time of chart lifecycle.

    TODO

    • [x] enable at dataset level
    • [x] enable at data level (for polarArea)
    • [x] test cases scale 0-positive (covered)
    • [x] test cases scale negative-0
    • [x] test cases scale positive-positive
    • [x] test cases scale negative-positive
    • [x] test cases scale negative-negative
    enhancement 
    opened by stockiNail 4
  • Remove destroy plugin hook and replaced with afterDestroy

    Remove destroy plugin hook and replaced with afterDestroy

    With CHART.JS 4, PR https://github.com/chartjs/Chart.js/pull/10549, the destroy plugin hook has been removed and replaced with afterDestroy. Currently, the version is not cleaning the states map.

    opened by stockiNail 2
  • Tooltip gradient doesn't working

    Tooltip gradient doesn't working

    I've some problem with gradient at tooltip. Can you guys give some advice?

    tooltip: {
    	gradient: {
    		backgroundColor: {
    			// linear-gradient(180deg, rgba(44, 110, 250, 0.7) 0%, rgba(2, 189, 173, 0.13) 100%);
    			axis: "x",
    			colors: {
    			          0: "rgba(2, 189, 173, 0.13)",
    			          5: "rgba(44, 110, 250, 0.2)",
    				 10: "rgba(2, 189, 173, 0.12)",
    			         15: "rgba(2, 189, 173, 0.13)",
                            }
    		},
    	},
    },
    
    opened by beastovsk 2
  • Webpack can't compile when I import

    Webpack can't compile when I import "gradient"

    I have an issue when I'm trying to import this library.

    I'm using webpack, and it doesn't compile the JS file and throws an error at the line:

    import gradient from 'chartjs-plugin-gradient';

    Here is the error message:

    "./node_modules/chartjs-plugin-gradient/dist/chartjs-plugin-gradient.esm.js" contains a reference to the file "chart.js/helpers". This file can not be found, please check it for typos or update it if the file got moved.

    If I try something like: import helpers from 'chart.js/helpers'; I have no error, so the helpers are found... But I keep having the issue at the line where I import gradient...

    Any idea?

    opened by vgross 0
Releases(v0.6.1)
  • v0.6.1(Dec 8, 2022)

  • v0.6.0(Dec 8, 2022)

    Essential Links

    • #43 Add compatibility to Chart.js version 4
    • #41 Bump engine.io and socket.io
    • #40 Bump socket.io-parser from 4.0.4 to 4.0.5 Thanks to @dependabot, @dependabot[bot], @kurkle and @stockiNail
    Source code(tar.gz)
    Source code(zip)
  • v0.5.1(Aug 24, 2022)

    Essential Links

    • #36 Bump 0.5.1
    • Fix typo in package.json/module
    • #34 Bump terser from 5.12.1 to 5.14.2 Thanks to @dependabot, @dependabot[bot] and @kurkle
    Source code(tar.gz)
    Source code(zip)
  • v0.5.0(Apr 12, 2022)

  • v0.4.1(Apr 12, 2022)

  • v0.4.0(Mar 30, 2022)

    Essential Links

    Enhancements

    • #29 Enable gradient styles on the legend items

    Bugs Fixed

    • #21 Skip the colorStop when the configured color is not valid

    Thanks to @stockiNail

    Source code(tar.gz)
    Source code(zip)
  • v0.3.0(Mar 24, 2022)

    Essential Links

    Enhancements

    • #16 Add support to time scale with colorStop option configured with formatted dates
    • #14 Add support for radialLinear scale with radial gradient

    Bugs Fixed

    • #18 Remove imported CHART.JS parts from distribution file
    • #19 Fix missing compatibility with CHART.JS version 2.x
    • #13 Bump ansi-regex from 5.0.0 to 5.0.1

    Thanks to @kurkle and @stockiNail

    Source code(tar.gz)
    Source code(zip)
  • v0.2.2(Mar 23, 2022)

    Essential Links

    • #12 Fix stops when scale is in reverse mode
    • #9 Use scale area to create the gradient instead of chart area Thanks to @kurkle and @stockiNail
    Source code(tar.gz)
    Source code(zip)
  • v0.2.1(Jul 30, 2021)

  • v0.2.0(Jul 26, 2021)

    Essential Links

    • [npm](https://www.npmjs.com/package/chartjs-plugin-gradient

    Enhancements

    • #5 Add changes to make plugin work on ChartJS V2 & V3 Thanks to @devotox and @kurkle
    Source code(tar.gz)
    Source code(zip)
  • v0.1.1(Nov 15, 2020)

  • v0.1.0(Jun 10, 2020)

Owner
Jukka Kurkela
Programmer of various languages and architectures since 1980's
Jukka Kurkela
This JavaScript library produces complementary gradients generated from the top 2 dominant colours in supplied images.

Grade Demo Check it out Install Download this repo and grab the grade.js file from the /docs/dist folder. Or install from npm: npm install grade-js Us

Ben Howdle 3.7k Jan 2, 2023
A Simple Dashboard Chart in Laravel Nova using Chart JS

A Simple Dashboard Chart in Laravel Nova using Chart JS. Starting create your own dashboard with Chart JS Integration can save your time and help you maintain consistency across standard elements such as Bar, Stacked, Line, Area, Doughnut and Pie Chart.

Kuncoro Wicaksono 177 Jan 4, 2023
Chart.js plugin to defer initial chart updates

Chart.js plugin to defer initial chart updates until the user scrolls and the canvas appears inside the viewport, and thus trigger the initial chart a

Chart.js 97 Nov 9, 2022
Bar Funnel Chart extension for Chart.js

Chart.BarFunnel.js Provides a Bar Funnel Chart for use with Chart.js Documentation To create a Bar Funnel Chart, include Chart.BarFunnel.js after Char

Chart.js 58 Nov 24, 2022
TradeX-chart is a trade chart written in plain (vanilla) JavaScript with minimal dependencies

TradeX-chart is a trade chart written in plain (vanilla) JavaScript with minimal dependencies; use it with any framework or backend.

null 24 Dec 12, 2022
:bar_chart: Re-usable, easy interface JavaScript chart library based on D3.js

billboard.js is a re-usable, easy interface JavaScript chart library, based on D3 v4+. The name "billboard" comes from the famous billboard chart whic

NAVER 5.4k Jan 1, 2023
Redefined chart library built with React and D3

Recharts Introduction Recharts is a Redefined chart library built with React and D3. The main purpose of this library is to help you to write charts i

recharts 19.4k Jan 2, 2023
:bar_chart: A D3-based reusable chart library

c3 c3 is a D3-based reusable chart library that enables deeper integration of charts into web applications. Follow the link for more information: http

C3.js 9.2k Jan 2, 2023
GPL version of Javascript Gantt Chart

dhtmlxGantt Getting started | Features | Follow us | License | Useful links dhtmlxGantt is an open source JavaScript Gantt chart that helps you illust

null 952 Dec 29, 2022
🍞📊 Beautiful chart for data visualization.

?? ?? Spread your data on TOAST UI Chart. TOAST UI Chart is Beautiful Statistical Data Visualization library. ?? Packages The functionality of TOAST U

NHN 5.2k Jan 2, 2023
:bar_chart: A library of modular chart components built on D3

Plottable Plottable is a library of chart components for creating flexible, custom charts for websites. It is built on top of D3.js and provides highe

Palantir Technologies 2.9k Dec 31, 2022
Chart image and QR code web API

QuickChart QuickChart is a service that generates images of charts from a URL. Because these charts are simple images, they are very easy to embed in

Ian Webster 1.3k Dec 25, 2022
📈 A small, fast chart for time series, lines, areas, ohlc & bars

?? μPlot A small (~35 KB min), fast chart for time series, lines, areas, ohlc & bars (MIT Licensed) Introduction μPlot is a fast, memory-efficient Can

Leon Sorokin 7.5k Jan 7, 2023
TChart.js - simple and configurable Bar and Line Chart library in Javascript

TChart.js Simple and configurable Bar and Line Chart library in Javascript Description TChart.js is a canvas-based simple Javascript Bar and Line Char

null 4 Mar 3, 2021
🍞📊 Beautiful chart for data visualization.

?? ?? Spread your data on TOAST UI Chart. TOAST UI Chart is Beautiful Statistical Data Visualization library. ?? Packages The functionality of TOAST U

NHN 5.2k Jan 6, 2023
The power of Chart.js in Jupyter !

The power of Chart.js in Jupyter Notebooks Installation You can install ipychart from your terminal using pip or conda: # using pip $ pip install ipyc

Nicolas H 68 Dec 8, 2022
Chart.js bindings for OCaml

chartjs-ocaml: OCaml bindings for Chart.js This library provides OCaml bindings for the Chart.js charting library and some popular plugins. Following

Alex Yanin 13 Aug 20, 2022
Java library for use with Chart.js javascript library

Chart.java Chart.java enables integration with the excellent Chart.js library from within a Java application. Usage example In Java: BarDataset datase

Marceau Dewilde 102 Dec 16, 2022
J2CL and GWT Charts library based on CHART.JS

Charba - J2CL and GWT Charts library based on CHART.JS What's Charba GWT Web toolkit doesn't have charting library available out of the box. There are

Pepstock.org 56 Dec 17, 2022