Stephen
Stephen

Reputation: 1183

Chart.js - Add gradient to line chart background

I am looking to create a line chart like this:

enter image description here

But I don't know how to add the gradient to the background. At this point I have the code to display the line correctly. This is the code for my chart:

     const ctx = document.getElementById("myChart");
      var speedData = {
        labels: [
          "Jan",
          "Feb",
          "Mar",
          "Apr",
          "May",
          "Jun",
          "Jul",
          "Aug",
          "Sep",
          "Oct",
          "Nov",
          "Dec"
        ],
        datasets: [
          {
            label: "Car Speed",
            data: this.car.energyConsumption,
            lineTension: 0,
            pointBackgroundColor: "#131921",
            pointBorderColor: "white",
            pointBorderWidth: 3,
            pointRadius: 6,
            borderColor: "white"
          }
        ]
      };

      var chartOptions = {
        legend: {
          display: false
        }
      };
      new Chart(ctx, {
        type: "line",
        data: speedData,
        options: chartOptions
      });
    }

Upvotes: 0

Views: 251

Answers (1)

Sunil Chaudhary
Sunil Chaudhary

Reputation: 4733

backgroundColor with createLinearGradient should help here. backgroundColor propertly takes in different types of colors. You need to create a gradient and specify the same.

Have created a sample snippet for you reusing your code. Follow lines 4-7 and line 34.

const ctx = document.getElementById("myChart");

// Create gradient here
const ctxForGradient = document.getElementById('myChart').getContext('2d');
const gradientFill = ctxForGradient.createLinearGradient(0, 500, 0, 50);
gradientFill.addColorStop(0, "rgba(255, 0, 0, 0.9)");
gradientFill.addColorStop(1, "rgba(0, 0, 255, 0.9)");

var speedData = {
  labels: [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec"
  ],

  datasets: [{
    label: "Car Speed",
    data: [7, 9, 5, 8, 9, 7, 6, 10, 4, 5, 7, 8, 9],
    lineTension: 0,
    pointBackgroundColor: "#131921",
    pointBorderColor: "white",
    pointBorderWidth: 3,
    pointRadius: 6,
    borderColor: "white",
    backgroundColor: gradientFill // Fill gradient here
  }]
};

var chartOptions = {
  legend: {
    display: false
  }
};
new Chart(ctx, {
  type: "line",
  data: speedData,
  options: chartOptions
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<canvas id="myChart"></canvas>

Hope it helps. Revert for any doubts/clarification.

Upvotes: 1

Related Questions