Chart.js - 添加渐变而不是纯色 - 实现解决方案

时间:2015-04-04 14:28:48

标签: javascript chart.js

我正在使用Chart.js,一切正常,但我想用渐变替换当前的颜色背景(fillColor:" rgba(250,174,50,0.5)")。 我有替换渐变的解决方案,但对我来说,用我糟糕的JS知识实现这一点太难了。对于认识JS的人来说,我觉得很容易。

所以我的Chart.js代码:

        <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>

here is solution with gradient有人可以尝试实现此渐变背景而不是我当前的纯色背景吗?谢谢你的帮助。

我尝试实现它,但其他功能不起作用(如scaleLabels等)。

4 个答案:

答案 0 :(得分:34)

您提供的链接非常清楚,您必须在数据集中的字段fillColor中放入linearGradient对象而不是纯颜色。你可以做复杂的渐变,但这里是一个简单的代码(改变相同橙色的不透明度):

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

您的完整数据集:

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]
            }
        ]

在此JSFiddle

中查看此操作

答案 1 :(得分:12)

注意:对于那些使用Chart.js较新版本(v2.7.0)的人来说,当你将@bviale的回复粘贴回你的代码库时,发现它无法正常工作;一些属性名称已更改:

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

您需要更新这些属性名称才能使其正常工作。

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

答案 2 :(得分:2)

为了在反应中使用,我做了以下方式 您需要将一个ID传递给您的组件,然后使用该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
              }
            }}
          />

    )
  }
}

这只是我的第二个答案,所以如果我在写作上有任何错误,请原谅我

答案 3 :(得分:1)

注意:从CODEPEN复制

此解决方案创建了一个带有红色主题的漂亮的垂直渐变图

    // ============================================
// As of Chart.js v2.5.0
// http://www.chartjs.org/docs
// ============================================

var chart    = document.getElementById('chart').getContext('2d'),
    gradient = chart.createLinearGradient(0, 0, 0, 400);

gradient.addColorStop(0, 'rgba(255, 0,0, 0.5)');
gradient.addColorStop(0.5, 'rgba(255, 0, 0, 0.25)');
gradient.addColorStop(1, 'rgba(255, 0, 0, 0)');


var data  = {
    labels: [ 'January', 'February', 'March', 'April', 'May', 'June' ],
    datasets: [{
            label: 'Custom Label Name',
            backgroundColor: gradient,
            pointBackgroundColor: 'white',
            borderWidth: 1,
            borderColor: '#911215',
            data: [50, 55, 80, 81, 54, 50]
    }]
};


var options = {
    responsive: true,
    maintainAspectRatio: true,
    animation: {
        easing: 'easeInOutQuad',
        duration: 520
    },
    scales: {
        xAxes: [{
            gridLines: {
                color: 'rgba(200, 200, 200, 0.05)',
                lineWidth: 1
            }
        }],
        yAxes: [{
            gridLines: {
                color: 'rgba(200, 200, 200, 0.08)',
                lineWidth: 1
            }
        }]
    },
    elements: {
        line: {
            tension: 0.4
        }
    },
    legend: {
        display: false
    },
    point: {
        backgroundColor: 'white'
    },
    tooltips: {
        titleFontFamily: 'Open Sans',
        backgroundColor: 'rgba(0,0,0,0.3)',
        titleFontColor: 'red',
        caretSize: 5,
        cornerRadius: 2,
        xPadding: 10,
        yPadding: 10
    }
};


var chartInstance = new Chart(chart, {
    type: 'line',
    data: data,
        options: options
});

签出这支笔https://codepen.io/grayghostvisuals/pen/gpROOz