23
votes

I am using Chart.js and everything is ok, but I want to replace current color background (fillColor : "rgba(250,174,50,0.5)") with a gradient. I have solution for replacing gradient but it's too dificult for me to implement this with my poor JS knowledge. I guess pretty easy for someone who know JS.

So my Chart.js code:

        <script>

        var data = {
            labels : ["02:00","04:00","06:00","08:00","10:00","12:00","14:00","16:00","18:00","20:00","22:00","00:00"],
            datasets: [
                {
                    fillColor : "rgba(250,174,50,0.5)",
                    strokeColor : "#ff6c23",
                    pointColor : "#fff",
                    pointStrokeColor : "#ff6c23",
                    pointHighlightFill: "#fff",
                    pointHighlightStroke: "#ff6c23",
                    data : [25.0,32.4,22.2,39.4,34.2,22.0,23.2,24.1,20.0,18.4,19.1,17.4]
                }
            ]
        };

        var options = {
            responsive: true,
            datasetStrokeWidth : 3,
            pointDotStrokeWidth : 4,
            tooltipFillColor: "rgba(0,0,0,0.8)",
            tooltipFontStyle: "bold",
            tooltipTemplate: "<%if (label){%><%=label + ' hod' %>: <%}%><%= value + '°C' %>",
            scaleLabel : "<%= Number(value).toFixed(0).replace('.', ',') + '°C'%>"
        };

        var ctx = document.getElementById("temp-chart").getContext("2d");
        var myLineChart = new Chart(ctx).Line(data, options);

    </script>

And here is solution with gradient. Can someone try implement this gradient background instead of my current solid background? Thanks for help.

I tryed implement it, but then other functions don't work (like scaleLabels etc.).

3
Do you still need help ?bviale
@jPO I posted an answerbviale
@bviale This is actually brilliant and quite stupid from me, that I didn't think of that :D Ofc it is simple 2D graphics so it has to accept the gradient. Thank you a lot!!jPO

3 Answers

58
votes

The link you provided was pretty clear, you have to put in the field fillColor in datasets a linearGradient object instead of a plain color. You can do complex gradients, but here is the code of a simple one (changing the opacity of the same orange) :

var gradient = ctx.createLinearGradient(0, 0, 0, 400);
gradient.addColorStop(0, 'rgba(250,174,50,1)');   
gradient.addColorStop(1, 'rgba(250,174,50,0)');

And your complete datasets :

datasets: [
            {
                fillColor : gradient, // Put the gradient here as a fill color
                strokeColor : "#ff6c23",
                pointColor : "#fff",
                pointStrokeColor : "#ff6c23",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "#ff6c23",
                data : [25.0,32.4,22.2,39.4,34.2,22.0,23.2,24.1,20.0,18.4,19.1,17.4]
            }
        ]

See it in action in this JSFiddle

28
votes

Note: For those people who is using newer version (v2.7.0) of Chart.js, find out that is not working while you're copy-paste @bviale's answer back to your code base; Some property names has changed:

fillColor -> backgroundColor
strokeColor -> borderColor
pointColor -> pointBackgroundColor
pointStrokeColor -> pointBorderColor

You will need to update those property names to make it work.

Reference: https://github.com/chartjs/Chart.js/blob/master/docs/charts/line.md#dataset-properties

7
votes

For using in react I did the following way you need to pass an id to your component and then fetch the element using that id

import React, { Component } from 'react'
import { Line } from 'react-chartjs-2'

export default class GraphComponent extends Component{
  constructor(props){
    super(props)
    this.state = {
      chartData: {}
    }
  }

  componentDidMount(){
    //your code
    var ctx = document.getElementById('canvas').getContext("2d")
    var gradient = ctx.createLinearGradient(0, 0, 0, 400)
    gradient.addColorStop(0, 'rgba(229, 239, 255, 1)')
    gradient.addColorStop(1, '#FFFFFF')
    const newData = {
      labels: [1, 1],
      datasets: [
        {
          label: 'usd',
          data: [1,1],
          backgroundColor: gradient,
          borderColor: this.props.border_color,
          pointRadius: 0
        }
      ]

    }
    this.setState({chartData: newData})
  }

  //more of your code

  render(){
    return(
          <Line
            id='canvas'//you need to give any id you want
            data={this.state.chartData}
            width={100}
            height={30}
            options={{
              legend: {
                display: false
              }
            }}
          />

    )
  }
}

this is only my second answer so please forgive me if I have made any mistakes in writing