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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29447579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:22:23  来源:igfitidea点击:

Chart.js - add gradient instead of solid color - implementing solution

javascriptchart.js

提问by John Cavalier

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.

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

So my Chart.js code:

所以我的 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>

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

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

回答by bviale

The link you provided was pretty clear, you have to put in the field fillColorin 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) :

您提供的链接非常清楚,您必须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)');

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

在这个JSFiddle 中查看它的实际效果

回答by AJ Hsu

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:

注意:对于那些使用 Chart.js 较新版本 (v2.7.0) 的人,当您将 @bviale 的答案复制粘贴回您的代码库时,发现它不起作用;一些属性名称已更改:

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

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

回答by Nishith

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

为了在反应中使用,我做了以下方式,您需要将一个 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
              }
            }}
          />

    )
  }
}

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

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

回答by Software Developer

NOTE: Copied From CODEPEN

注意:从CODEPEN复制

This solution creates a nice vertical gradient graph with a red theme

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

    // ============================================
// 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
});

check out this pen https://codepen.io/grayghostvisuals/pen/gpROOz

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