如何在chart.js中将`fillColor`作为渐变?

时间:2019-07-03 10:47:42

标签: javascript css chart.js

我正在使用chart.js包。我只使用了一种颜色rgba(),但我想使用渐变色作为rgba而不是fillColor

这是我下面的chart.js代码:

var buyerData = {
    labels: [
        "Jan",
        "Feb",
        "Mar",
        "Apr",
        "May",
        "Jun",
        "Jul",
        "Aug",
        "Sep",
        "Oct",
        "Nov",
        "Dec"
    ],
    datasets: [
        {
            fillColor: "rgba(129,61,126,0.37)",
            strokeColor: "#813D7E",
            pointColor: "#813D7E",
            pointStrokeColor: "#9DB86D",
            data: [30, 40, 32, 90, 150, 20, 30, 50, 150, 100, 200, 250]
        }
    ]
};
// get line chart canvas
var buyers = document.getElementById("buyers").getContext("2d");
// draw line chart
new Chart(buyers).Line(buyerData);

1 个答案:

答案 0 :(得分:1)

var ctx = document.getElementById("buyers").getContext("2d")
var gradient = ctx.createLinearGradient(0, 0, 0, 175);
gradient.addColorStop(0, "black");
gradient.addColorStop(1, "white");

 var buyerData = {

    labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
    datasets: [{
      fillColor: gradient,
      strokeColor: "#813D7E",
      pointColor: "#813D7E",
      pointStrokeColor: "#9DB86D",
      data: [30, 40, 32, 90, 150, 20, 30, 50, 150, 100, 200, 250]
    }]
  }
  // get line chart canvas
  var buyers = document.getElementById('buyers').getContext('2d');
  // draw line chart
  new Chart(buyers).Line(buyerData);

Working fiddle

Learn more about createLinearGradient method

希望这有帮助:)